javascript - 是否可以通过 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”。
解决方案
我就是这样做的: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()})
我希望它有所帮助。
推荐阅读
- firebase - 如何使用网站将身份验证令牌返回给谷歌助手?
- c# - 在 WPF 中显示系统时间:调度程序计时器
- python - Python 中的一个程序,它以小写且不带换行符的形式打印字母 - 除了 q 和 e
- javascript - AJAX 和 Facebook API
- ipython - ImportError:没有名为“pvlib”的模块
- mysql - 从表 1 中获取所有值并从表 2 中获取一个字段的值
- java - JOptionPane 输入后关闭,但应打开第二个输入对话框
- ios - 如何从反应原生页面快速打开现有的 ViewController?
- python - 在 python 2.7 中使用长链调用模拟静态函数调用
- android - 如何在android中集成paypal支付网关