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

标签 javascript html

我正在一个网络开发实验室工作,但我的图像没有显示。我在引用图像时做错了什么吗?这是图像本身的链接: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>

最佳答案

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

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

关于javascript - HTML5/JS 不在 Canvas 中渲染图像。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14879326/

相关文章:

javascript - 循环遍历数组并延迟函数

html - 如何在html/css中移动下拉菜单?

javascript - 如何检查动画循环中是否按下了空格键? (在 JavaScript 中)

javascript - if语句变量和数组

html - 如何重置 panzoom.js 的坐标?

html - 变形后的 child 包含奇怪的 parent 宽度

javascript - CSS 未在 Chrome 上加载 - 缓存问题

html - DIV 在有子元素时移动

javascript - DataTables:如何将类设置为表格行单元格(而不是表格标题单元格!)

javascript - 我无法使用在同一对象内创建的方法来修改对象的属性。我正在尝试使用 foreach 然后 console.log 未定义