我有4个基座,它们都使用要在屏幕上连续绘制的同一图像。它们都是画布。我加载图像,并使用onload函数和canvas上下文在onload函数中绘制图像。问题是,只有最后一个显示了图像,其他的都在那里,我可以将它们打印到控制台,但是看不到图像。
这显然很简单,但是当您被卡住时,有时很难看到明显的错误。
代码:
function setup_bases(){
var top = 460;
var left = screen_left + 170;
var base_img_location = img_dir + "base.png";
var base;
for(c=0; c < 4; c++){
var id= "base" + c;
base = document.createElement('canvas');
console.log("base = ")
console.log(base);
var ctx = base.getContext("2d");
var rule = "#" + id + " { position: absolute; top: "+ top + "px; left: " + left + "px; width: 60px; height: 44px; }"
stylesheet.insertRule(rule);
base.setAttribute("id", id);
base.setAttribute("class", "base");
base.setAttribute("position", "absolute")
base.setAttribute("width", "60px");
base.setAttribute("height", "44px");
base.style.left = left + "px";
base.style.top = top + "px;"
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
}
img.src = base_img_location;
document.getElementById("main").appendChild(base);
console.log(base)
left += 230;
console.log("img.src =");
console.log(img.src);
}
}