0

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

(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:类型错误

我哪里错了?

4

1 回答 1

0

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

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

    function resizeCanvas() {
    console.log("resize");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        if(imageObj){
            drawStuff(); 
        }
    }
    resizeCanvas();
于 2013-05-01T23:24:35.290 回答