Search code examples
javascripthtmlimagecanvashtml5-canvas

Add image as the background of an canvas


I want to make the background of my canvas an image, but not sure how to do it, what I've tried isn't working. I'm also not sure how to make it so the image isn't stretched or squished when the size of the window changes, any help would be appreciated.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>shark?</title>
    <style>
        html, body {
            height: 100%;
            width: 100%;
            margin: 20;
            overflow: hidden;
        }
        .container {
            display: flex;
            flex-direction: column; 
            align-items: center;
            justify-content: center;
            height: 100%;
            width: 100%;
        }
        h1 {
            margin-top: 10px; 
        }
        canvas {
            background-image: url ("c:\background\backg.jpg");
            margin: 50px; 
            flex: 1;
            width: calc(100% - 100px);
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>shark?</h1>
        <canvas></canvas>
    </div>
</body>
</html>

Solution

  • You should remove space in url ("...") (should be url("...")).

    To make it more adaptive to window resize add this to styles:

    canvas {
      ...
      background-size: cover;
      background-position: center;
    }
    

    If you also plan to draw something on this canvas and make it also adaptive, you need to

    1. Recalculate and set new width and height for canvas on resize events.
    2. Calculate new coordinates to make drawing behave as needed or use translate/scale methods of context object.
    3. Do not forget about clearRect method on the first line of drawing part.