Search code examples
javascripthtmlcanvasbackground-image

HTML canvas displays image below canvas instead of inside canvas


I am trying to display a background image inside HTML5 canvas. I have made sure that the image and the html file are in the same folder, therefore, the image is displaying. I have also tried to resize the image in order to make sure the image is not too large for the canvas, however, the image keeps displaying under the canvas instead of inside the canvas. My code is below:

<!DOCTYPE html>
<html lang="en"> 
<head>
    <meta charset="UTF-8">
    <title>Opening screen</title>
</head>
<body>
<img>
<canvas id="canvas"
        style =
                "width: 700px;
                 height: 500px;
                 border: 1px solid #000000;
                 padding-left: 0;
                 padding-right: 0;
                 margin-top: 40px;
                 margin-left: auto;
                 margin-right: auto;
                 display: block;">
</canvas>
<img id="sky"  src="sky.png">
<script>
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var img = document.getElementById("sky");
    ctx.drawImage(img, 10, 10);
</script>
</body>
</html>

Solution

  • you can remove your img tags and set background for your canvas

    <canvas id="canvas"
            style =
                    "width: 700px;
                      background: url(https://placekitten.com/1000/1000) no-repeat top center;
                      background-size:cover;
                     height: 500px;
                     border: 1px solid #000000;
                     padding-left: 0;
                     padding-right: 0;
                     margin-top: 40px;
                     margin-left: auto;
                     margin-right: auto;
                     display: block;">
    </canvas>