用一个onload绘制图像数组?

时间:2015-02-16 23:52:12

标签: javascript html5-canvas

我想用一个onload函数绘制一行图像。 我试过这段代码

for(i = 0; i < 8; i++){
var canvas = document.getElementById('ctx');
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.src = "thumb.png";
imageObj.setAtX = i * 10;
imageObj.setAtY = i * 10;
imageObj.onload = function() {
context.drawImage(this, this.setAtX, this.setAtY);
};
}

(在java-script中)

3 个答案:

答案 0 :(得分:1)

// put the paths to your images in imageURLs[]
var imageURLs=[];  
imageURLs.push("image1.png");
imageURLs.push("image2.png");

// the loaded images will be placed in imgs[]
var imgs=[];

var imagesOK=0;
loadAllImages(start);

function loadAllImages(callback){
    for (var i=0; i<imageURLs.length; i++) {
        var img = new Image();
        imgs.push(img);
        img.onload = function(){ 
            imagesOK++; 
            if (imagesOK>=imageURLs.length ) {
                callback();
            }
        };
        img.onerror=function(){alert("image load failed");} 
        img.crossOrigin="anonymous";
        img.src = imageURLs[i];
    }      
}

function start(){

    // the imgs[] array now holds fully loaded images
    // the imgs[] are in the same order as imageURLs[]

}

答案 1 :(得分:0)

只需重复使用图片,当图片加载然后在循环中绘制它 - 重新组织如下:

var canvas = document.getElementById('ctx');
var context = canvas.getContext("2d");
var imageObj = new Image();

imageObj.onload = function() {
    for(var i = 0; i < 8; i++) context.drawImage(this, i * 10, i * 10);
    // .. call next step from here
};

imageObj.src = "thumb.png";

尽量避免在本机对象上设置新属性。在这种情况下,您不需要它,只需在图像加载时进行迭代。

答案 2 :(得分:0)

var imageObj = [];
for(var i=0;i<images.length;i++){
  iy = parseInt(i/6) * 200;
  ix = parseInt(i%6) * 200;
  imageObj[i] = new Image();
  imageObj[i].src = images[i];
  // to set additinal parameter
  imageObj[i].ix = JSON.parse(JSON.stringify(ix));
  imageObj[i].iy = JSON.parse(JSON.stringify(iy));
  // console.log(imageObj);
  imageObj[i].onload = function() {
    console.log(this.ix);
    console.log(this.iy);
    ctx.drawImage(this, this.ix, this.iy, 200, 200);
  };
}