Base_Image未在循环中定义(for)

时间:2014-01-28 14:28:51

标签: javascript html5-canvas

我有这个代码,他将图像插入画布:

 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

那么,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

一些修正:

  • 将base_image声明为数组
  • base_image.src [q]应为base_image [q] .src
  • 在尝试绘制图像之前,您需要确保所有图像都已加载。
  • 你有0.png,...,5.png图片加载你只是0I的drawImage。

祝你的项目好运!

以下是示例代码:

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';

    }

}