[英]How to improve repetitive js code
我将显示代码的一小部分,它实际上包含12张图像,而不是我显示的3张图像。 我开始创建自己拥有的不同图像,然后在需要时将其绘制到画布上。 正如您所看到的那样,该代码非常重复,使用switch语句执行相同的操作12次,唯一的区别是this.img
中的this.img
。 也许有更好的方法来创建图像12次。
let Game = function (element) {
const matrix = [];
while (h--) {
matrix.push(new Array(w).fill(0));
}
this.matrix = matrix;
this.canvas = element.querySelector('canvas.tetris');
this.ctx = this.canvas.getContext('2d');
// create all the images
this.img1 = new Image();
this.img1.src = 'img/1.gif';
this.img2 = new Image();
this.img2.src = 'img/2.gif';
this.img3 = new Image();
this.img3.src = 'img/3.gif';
// Render the canvas board
let lastTime = 0;
this._update = (time = 0) => {
const deltaTime = time - lastTime;
lastTime = time;
this.drawCanvas();
this.gameAnimation = requestAnimationFrame(this._update);
};
};
Game.prototype.drawCanvas = function () {
// matrix[y][x] is the number of the img name
for (let y = 0; y < matrix.length; y += 1) {
for (let x = 0; x < matrix[y].length; x += 1) {
switch (matrix[y][x]) {
case 1:
this.ctx.drawImage(this.img1, x, y, 0.99, 0.99);
break;
case 2:
this.ctx.drawImage(this.img2, x, y, 0.99, 0.99);
break;
case 3:
this.ctx.drawImage(this.img3, x, y, 0.99, 0.99);
break;
}
}
}
}
我希望有人知道更好的解决方案,而不是使用switch语句。
由于案例1对应于this.img1
,案例2对应于this.img2
,依此类推,只需使用括号符号代替:
for (let x = 0; x < matrix[y].length; x += 1) {
const imgIndex = matrix[y][x];
this.ctx.drawImage(this['img' + imgIndex], x, y, 0.99, 0.99);
}
创建图像时,您可以执行类似的操作:
for (let i = 1; i < 13; i++) {
this['img' + i] = new Image();
this['img' + i].src = 'img/' + i + '.gif';
}
但是您可能会考虑使用数组代替,例如
this.images = Array.from(
{ length: 12 },
(_, i) => {
const img = new Image();
img.src = 'img/' + (i + 1) + '.gif';
return img;
}
);
然后在矩阵循环中访问适当的索引:
for (let x = 0; x < matrix[y].length; x += 1) {
const imgIndex = matrix[y][x] - 1;
this.ctx.drawImage(this.images[imgIndex], x, y, 0.99, 0.99);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.