以下是代码:
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
,则不会绘制图像。为什么呢?
答案 0 :(得分:3)
因为您的图片尚未加载。 由于你的1秒超时,他们有足够的时间加载。
从MDN https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images
查看此示例您需要使用类似方法 - 请参阅select * from (
select fd.name field_name, s.text_value, s.id_object
from custom_field_str s
join catalogues c on c.id_object = 'cA1'
join attribute_definitions ad on ad.id_field = s.id_field
and c.id_object = ad.id_object_type and ad.text_table_name = 'custom_field_str'
join field_definitions fd on ad.id_field = fd.id_object )
pivot (max(text_value)
for field_name in ('field1' as field1,'field2' as field2,'field3' as field3))
img.onload()