我有3个图片“名称”,“ X位置”,“ Y位置”,“比例”和“颜色值”存储在各种数组中,例如:
pictureNames["blahblah1, "somePic2", "anotherPic3"];
pictureXcoordinates[0, 43, 56];
pictureYcoordinates[0, 10, 20];
pictureScales[100, 100, 100]; //meaning percent
pictureColorRvalue[0, 0, 0];
pictureColorGvalue[0, 0, 0];
pictureColorBvalue[0, 0, 0];
PNG图像已预加载并分配了变量,例如picture0,picture1,picture2。
我试图通过制作一个for循环以将每张图片及其尺寸和坐标绘制到其OWN canvas元素中,然后通过获取图像数据对其进行着色来节省很多代码行。像这样:
var counter;
for(counter = 0; counter <= 2; counter++){
firstCtx.drawImage(picture1 ,pictureXcoordinates[counter], pictureYcoordinates[counter], picture0.width, picture0.height);
firstCtx.restore();
var imgData = firstCtx.getImageData(pictureXcoordinates[counter], pictureYcoordinates[counter], canvasW, canvasH);
var i;
for (i = 0; i < imgData.data.length; i += 4) {
imgData.data[i] = pictureColorRvalue[counter];
imgData.data[i+1] = pictureColorGvalue[counter];
imgData.data[i+2] = pictureColorBvalue[counter];
}
firstCtx.putImageData(imgData, shapePositionX[counter], shapePositionY[counter]);
firstCtx.restore();
...但是我不知道如何使用计数器变量来引用“ firstCtx”,secondCtx”,“ thirdCtx”。...应该/可以重命名画布内容“ canvas1Ctx”,“ canvas2Ctx”,等等...并用“ canvas” + counter +“ Ctx”或类似名称引用它们?并同时引用“ picture0”,“ picture1”和“ picture2”。
答案 0 :(得分:0)
这就是我要这样做的方式:Y将创建一类对象Picture
,每个对象都有x
,y
等...以及一个处理绘制过程的函数
let picturesArray = []
class Picture{
constructor(x,y,width,height,scale,color,pictureName,canvas){
this.x = x;
this.y = y;
this.w = width;
this.h = height;
this.scale = scale;
this.color = color;
this.picture = pictureName;
this.canvas = canvas;
this.ctx = this.canvas.getContext("2d")
}
draw(){
this.ctx.drawImage(this.picture ,this.x, this.y, this.w, this.h);
this.imgData = this.ctx.getImageData(this.x, this.y, this.canvas.width, this.canvas.height);
for (let i = 0; i < imgData.data.length; i += 4) {
this.imgData.data[i] = this.color.r;
this.imgData.data[i+1] = this.color.g;
this.imgData.data[i+2] = this.color.b;
}
this.canvas.putImageData(this.imgData, this.x, this.y);
}
}
接下来,我将创建对象图片并将新图片推入图片数组:
picturesArray.push(new Picture(x,y,width,height,scale,color,pictureName,canvas));
最后,您使用for
循环或forEach
绘制所有图片
picturesArray.forEach(p=>{p.draw()})
希望对您有帮助。