Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 524
Barry B Benson Avatar asked Oct 20 '25 22:10

Barry B Benson


1 Answers

The image hasn't loaded/downloaded by the time you're trying to insert it into the canvas.

You can add your code to the window.onload function and it should work

window.onload = function() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var img = document.getElementById("sky");
    ctx.drawImage(img, 10, 10);
}

As for why it's displaying below your canvas, you have an img element with that image in, placed after the canvas.

like image 81
George Avatar answered Oct 22 '25 11:10

George



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!