简体   繁体   中英

Image is not drawing on canvas (HTML5)

I am trying to draw an image on a canvas, in HTML5 . For some reason, the image simply isn't drawn onto the canvas , and there are no errors in the console. Here is my code:

<!DOCTYPE html>
<html>
    <body>
        <img id="image" src="Images/player.png"></img>
        <canvas id="canvas" width="1000" height="750"></canvas>
        <script>
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext("2d");
            var image = document.getElementById("image");

            context.fillStyle = "lightblue";
            context.fillRect(0, 0, 1000, 750);
            context.drawImage(image, 0, 0);
        </script>
    </body>
</html>

Can somebody help? Thanks.

You need to add an event listener to the img tag called load . Then in the callback you can call drawImage with the provided img element.

You can do something like this - I have added one stackoverflow image for representation:

 const canvas = document.getElementById("canvas"); const context = canvas.getContext("2d"); const image = document.getElementById("image"); context.fillStyle = "lightblue"; context.fillRect(0, 0, 1000, 750); image.addEventListener('load', e => context.drawImage(image, 0, 0));
 <img id="image" src="https://stackoverflow.blog/wp-content/themes/stackoverflow-oct-19/images2/header-podcast.svg" height="100px"></img> <canvas id="canvas" width="1000" height="750"></canvas>

From the documentation: Drawing an image to the canvas

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM