HTML5/JS不在画布中渲染图像

HTML5/JS Not Rendering Image in Canvas.

本文关键字:布中渲 图像 JS HTML5      更新时间:2023-09-26

我正在一个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>

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

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!');
    }
}