[英]Is it possible to reference multiple html5 canvases and variable names through a for loop?
我有3個圖片“名稱”,“ Xpositions”,“ Ypositions”,“ scale”和“ color values”存儲在各種數組中,如下所示:
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”進行引用。
我就是這樣做的: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()})
希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.