2015-07-10 43 views
0

下面是代碼:爲什麼在將圖像繪製到畫布時需要延遲?

var spriteFolder = "../../assets/Painter/sprites/"; 
var sprites = {}; 
sprites.background = new Image(); 
sprites.background.src = spriteFolder + "spr_background.jpg"; 
sprites.cannon_barrel = new Image(); 
sprites.cannon_barrel.src = spriteFolder + "spr_cannon_barrel.png"; 
sprites.cannon_red = new Image(); 
sprites.cannon_red.src = spriteFolder + "spr_cannon_red.png"; 
sprites.cannon_green = new Image(); 
sprites.cannon_green.src = spriteFolder + "spr_cannon_green.png"; 
sprites.cannon_blue = new Image(); 
sprites.cannon_blue.src = spriteFolder + "spr_cannon_blue.png"; 


var Canvas2D = { 
    canvas: undefined, 
    canvasContext: undefined 
}; 

Canvas2D.initialize = function(canvasName) { 
    Canvas2D.canvas = document.getElementById(canvasName); 
    Canvas2D.canvasContext = Canvas2D.canvas.getContext("2d"); 
}; 

Canvas2D.clear = function() { 
    Canvas2D.canvas.clearRect(0, 0, Canvas2D.canvas.width, Canvas2D.canvas.height); 
}; 

Canvas2D.drawImage = function(sprite, position, rotation, origin) { 
    Canvas2D.canvasContext.save(); 
    Canvas2D.canvasContext.translate(position.x, position.y); 
    Canvas2D.canvasContext.rotate(rotation); 
    Canvas2D.canvasContext.drawImage(sprite, 
     0, 0, sprite.width, sprite.height, 
     -origin.x, -origin.y, sprite.width, sprite.height 
    ); 
    Canvas2D.canvasContext.restore(); 
}; 

function init() { 
    Canvas2D.initialize("myCanvas"); 
    setTimeout(function() { 
     Canvas2D.canvasContext.drawImage(sprites.background, 0, 0); 
    }, 1000); 
} 
document.addEventListener("DOMContentLoaded", init); 

如果我不使用setTimeout,則圖像不被繪製。爲什麼?

+1

我懷疑的是,圖像還沒有完成加載? –

回答

2

因爲您的圖像尚未加載。 感謝您的1秒超時,他們有足夠的時間加載。

看一看從MDN https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images

這個例子中你需要使用類似的方法 - 看img.onload()

function draw() { 
     var ctx = document.getElementById('canvas').getContext('2d'); 
     var img = new Image(); 
     img.onload = function(){ 
     ctx.drawImage(img,0,0); 
     ctx.beginPath(); 
     ctx.moveTo(30,96); 
     ctx.lineTo(70,66); 
     ctx.lineTo(103,76); 
     ctx.lineTo(170,15); 
     ctx.stroke(); 
     }; 
     img.src = 'https://mdn.mozillademos.org/files/5395/backdrop.png'; 
    }