Reputation: 197
I will show a small part of the code that actually has 12 images instead of 3 that I show. I start out to create the different images I have and then I draw it to the canvas when needed. As you can see the code is very repetitive with an switch statement that does the same thing 12 times, the only difference is the number in the this.img
. Maybe there allso is a better way to create the images 12 times.
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;
}
}
}
}
I hope somebody knows a better solution instead of the switch statement.
Upvotes: 1
Views: 44
Reputation: 370689
Since case 1 corresponds to this.img1
, case 2 corresponds to this.img2
, and so on, just use bracket notation instead:
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);
}
You can do something similar when creating the images:
for (let i = 1; i < 13; i++) {
this['img' + i] = new Image();
this['img' + i].src = 'img/' + i + '.gif';
}
But you might consider using an array instead, eg
this.images = Array.from(
{ length: 12 },
(_, i) => {
const img = new Image();
img.src = 'img/' + (i + 1) + '.gif';
return img;
}
);
and then access the appropriate index in the matrix loop:
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);
}
Upvotes: 4