HTML5 / JS不在Canvas中渲染图像。

时间:2013-02-14 16:21:56

标签: javascript html html5

我正在开发一个Web开发实验室,但我的图像没有显示出来。在引用图像时我有什么问题吗?以下是图片本身的链接: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>

1 个答案:

答案 0 :(得分: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!');
    }
}