用一个加载项绘制图像阵列

draw array of images with one onload?

本文关键字:加载项 绘制 图像 阵列 一个      更新时间:2023-12-27

我想用一个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脚本中)

// 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[]
}

只需重用图像,当图像加载时,将其绘制成循环-像这样重新组织:

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

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

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);
  };
}