我无法在 html5 中的画布中获取图像,该怎么办?

2022-01-17 00:00:00 image html html5-canvas

我已经从我的 w3schools 检查了这段代码,它运行良好.

I have checked this code from my w3schools where its working well.

但是当我在浏览器中运行这段代码时,它不起作用.

But when I run this code in my browser, it's not working.

图像未显示在画布中.此外,我在其他地方的 w3schools 浏览器中尝试了相同的代码,但它仍然无法在该浏览器中运行.

The image does not get displayed in the canvas. Also, I tried the same code in w3schools browser somewhere else, but still it's not working in that browser either.

<!DOCTYPE html>
<html>
    <body>
        <p>Image to use:</p>
        <img id="scream" src="flower.jpg" alt="The Scream" width="220" height="277"><p>Canvas:</p>
        <canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">

        <script>
            var c=document.getElementById("myCanvas");
            var ctx=c.getContext("2d");
            var img=document.getElementById("scream");
            ctx.drawImage(img,10,10);
        </script>
    </body>
</html>

推荐答案

问题是图片的加载是异步的,所以你的Javascript代码可能在图片加载完成之前就已经运行了.因为当 ctx.drawImage(img, 10, 10) 被称为 img 时没有完整的数据并且在画布上什么也没有.

The problem is that load of an image is asynchronous, so your Javascript code might run before the image finish his loading. Because of that when ctx.drawImage(img, 10, 10) is called img have no complete data and draws nothing on canvas.

要解决您需要等待图像完全加载的问题.Javascript 让您能够设置一个函数以在图像完全加载时运行.

To solve that you need to wait the image to completely load. Javascript give you the ability to setup a function to run when an image is completely loaded.

所有依赖于图像数据的代码都应该放在 onload 回调中.

All code that depends of the image data should be put inside the onload callback.

img.onload = function(){ 
    ctx.drawImage(img,10,10);
}

带有修改部分的脚本:

<script>
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    var img=document.getElementById("scream");
    img.onload = function(){ 
        ctx.drawImage(img,10,10);
    }
</script>

如果 src 正确,无论图像是从 html 标记加载还是使用 new Image() 在 Javascript 中动态创建,onload 方法适用于两者.

If the src is correct doesn't matter if the image is loaded from a html tag or created dynamically in Javascript with new Image(), the onload method works for both.

相关文章