尝试将图像绘制到html5画布时键入错误

时间:2013-05-01 21:39:25

标签: html5-canvas

我只是尝试使用以下代码绘制图像:

(function() {
        var canvas = document.getElementById('canvas'),
            context = canvas.getContext('2d');

        // resize the canvas to fill browser window dynamically
        window.addEventListener('resize', resizeCanvas, false);

        function resizeCanvas() {
                canvas.width = window.innerWidth;
                canvas.height = window.innerHeight;
                drawStuff(); 
        }
        resizeCanvas();

       var imageObj = new Image();

      imageObj.onload = function() {
        drawStuff();
      };
      imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';

        function drawStuff() {
           context.drawImage(imageObj, 69, 50);
        }
})();

但我收到了错误

  

未捕获的TypeError:输入错误

我哪里错了?

1 个答案:

答案 0 :(得分:0)

您的调整大小处理程序在imageObj.onload之前被触发。

然后resizeCanvas()调用drawStuff,它试图绘制一个不存在的图像对象并崩溃!

    function resizeCanvas() {
    console.log("resize");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        if(imageObj){
            drawStuff(); 
        }
    }
    resizeCanvas();