首页 > 解决方案 > 是否可以通过 for 循环引用多个 html5 画布和变量名?

问题描述

我有 3 个图片“名称”、“Xpositions”、“Ypositions”、“比例”和“颜色值”存储在各种数组中,如下所示:

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 画布元素中,然后通过获取图像数据对它们进行着色,从而节省多行编码。所以像这样:

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”。

标签: javascriptfor-loopreferencehtml5-canvas

解决方案


我就是这样做的:Y 将创建一个对象类Picture,每个对象都有它的xy等等......以及一个处理绘图过程的函数。

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

我希望它有所帮助。


推荐阅读