0

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

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

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

<!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>
4

3 回答 3

1

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.

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.

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

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

Your script with the modified parts:

<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>

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.

于 2013-05-29T13:05:28.940 回答
1

我会直接使用图像,而不是将其从<img>-tag中取出

var c = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var imageObj = new Image();

imageObj.onload = function() {
      ctx.drawImage(imageObj, 10, 10);
};
imageObj.src = 'flower.jpg';
于 2013-05-29T12:11:27.127 回答
0

您可能需要在加载时运行 javascript,而不是直接在正文中运行。将您的 javascript 更改为此,它应该可以工作(至少它在这个 fiddle中可以):

function setup_canvas() {
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    var img=document.getElementById("scream");
    ctx.drawImage(img,10,10);
}

window.onload = setup_canvas;

此外,正如此线程中所述,显式设置window.onload不是一个很好的做法,因为它可能会被后续脚本覆盖,因此对于测试以外的任何内容,您都希望使用框架或addEventListener/ attachEvent

于 2013-05-29T12:12:53.213 回答