2

我在一个网络开发实验室工作,但我的形象没有出现。引用图像时我做错了什么吗?这是图像本身的链接:http: //tuftsdev.github.com/WebProgramming/assignments/pacman10-hp-sprite.png

注意:我将图像复制到本地目录中,所以我知道引用是正确的。

 <!DOCTYPE html>
 <html>
 <head>
     <title>Ms. Pacman</title>
     <script>
         function draw() {
             canvas = document.getElementById('simple');

             // Check if canvas is supported on browser
             if (canvas.getContext) {
                ctx = canvas.getContext('2d');
                var img = new Image();
                img.src = '"pacman10-hp-sprite.png';
                ctx.drawImage(img, 10, 10);
             }
             else {
                alert('Sorry, canvas is not supported on your browser!');
             }
       }
     </script>
  </head>

 <body onload="draw();">
     <canvas id="simple" width="800" height="800"></canvas>
 </body>
 </html>
4

1 回答 1

2

实际加载图像后,您需要设置回调并将图像绘制到画布上:

function draw() {
    canvas = document.getElementById('simple');

    // Check if canvas is supported on browser
    if (canvas.getContext) {
        ctx = canvas.getContext('2d');
        var img = new Image();

        // If you don't set this callback before you assign
        // the img.src, the call ctx.drawImage will have 
        // a null img element. That's why it was failing before
        img.onload = function(){
            ctx.drawImage(this, 10, 10);
        };

        img.src = "pacman10-hp-sprite.png";
    } else {
        alert('Sorry, canvas is not supported on your browser!');
    }
}
于 2013-02-14T16:25:48.103 回答