如何动态调用图像?

时间:2013-03-27 18:44:18

标签: javascript html5

我想拨打pic1pic2 ... picn使用名为image的对象。

image对象示例代码。

for (var src in images) {
    image[src] = new Image();
    image[src].onload = function () {
        counter++;
    };
    image[src].src = images[src];
}

image.pic1,image.pic2 ......image.picn

image:Object我尝试用几种方法来调用图像对象:

col = 1; image.pic+col: NaN image.'pic'+col: image.'pic'+'1': image.pic+'1': "undefined1" image.[pic+col] image.[pic1]:

运行下一个代码:

for(var col = 1; col < n ; col++) {
    CanvasA.drawImage(image.pic1, x, y, 300, 300);
    //CanvasA.drawImage(image.pic2, x, y, 300, 300);
    //...............
    //...............
    //CanvasA.drawImage(image.picn, x, y, 300, 300);
}

这是代码的一部分:

for(var squer = 1;squer < 8 ; squer++ ) {
    y = (squer * 100)-100;

    for(var col = 0; col < 14 ; col++) {
        if (map.raw[squer][col+1] == 1) {
            x = ((col+1) * 100)-100;
            CanvasA.drawImage(image.LEAF1, x, y, BACKGROUND.LEAF.w, BACKGROUND.LEAF.h);
            //CanvasA.fillRect(x,y,100,100);
        }   
    }
}

3 个答案:

答案 0 :(得分:0)

你有一个错字: “图像”应该是“图像”;

尝试:

var counter = 0;

for (var src in image) {
    image[src] = new Image();
    image[src].onload = function () {
        counter++;
    };
    image[src].src = images[src];
}

答案 1 :(得分:0)

将新创建的图像推送到另一个阵列

var imageObjects = [];
for (var src in images) {
    image[src] = new Image();
    ...
    imageObjects.push( image[ src ] );
}

然后

for(var col = 1; col < n ; col++){
    for ( var i; i < imageObjects.length; i ++ ){
        CanvasA.drawImage( imageObjects[i], x, y, 300, 300 );
    }
}

答案 2 :(得分:0)

应该是

image.["pic" + col]