我有这个代码,他将图像插入画布:
function image(){
base_image = new Image();
base_image.src = '0.png';
base_image.onload = function(){
ctx.drawImage(base_image,243,68,24,24);
}
}
但是我想自动化这段代码,并且我采用了这种格式
function image(){
for(q=0;q<6;q++){
base_image[q] = new Image();
base_image.src[q] = q + '.png';
base_image[q].onload = function(){
ctx.drawImage(base_image[0],243,68,24,24);
ctx.drawImage(base_image[1],478,48,24,24);
ctx.drawImage(base_image[2],113,477,24,24);
ctx.drawImage(base_image[3],445,144,24,24);
ctx.drawImage(base_image[4],789,220,24,24);
}
}
}
控制台给出了这个消息
Base_Image is not definied
那么,有人可以帮助我吗?
答案 0 :(得分:1)
一些修正:
祝你的项目好运!
以下是示例代码:
function image(){
var base_image=[];
var loaded=0;
for(q=0;q<6;q++){
base_image[q] = new Image();
base_image[q].onload = function(){
if(++loaded==6){
ctx.drawImage(base_image[0],243,68,24,24);
ctx.drawImage(base_image[1],478,48,24,24);
ctx.drawImage(base_image[2],113,477,24,24);
ctx.drawImage(base_image[3],445,144,24,24);
ctx.drawImage(base_image[4],789,220,24,24);
}
}
base_image[q].src ="house16x16.png"; // q + '.png';
}
}