Reputation: 157
I'm making a chess game. My current idea is after move one piece, I will redraw all board(This may be bad at now)
I have a problem with redraw image, one piece image only draw once time at first and never redraw.
Here is my drawPiece()
function:
drawPieces() {
const ctx = this.canvas.getContext('2d');
const piecesOnBoard = this.boardStatus.split("_");
for (let key in this.images) {
const image = this.images[key];
image[1].onload = function () {
for (let i = 0; i < piecesOnBoard.length; i++) {
let x = piecesOnBoard[i].charAt(0);
let y = piecesOnBoard[i].charAt(1);
let piece = piecesOnBoard[i].substring(2);
if (image[0] === piece) {
ctx.drawImage(image[1], (Canvas.CELL_SIZE + 1) * y + 1, (Canvas.CELL_SIZE + 1) * x + 1, Canvas.CELL_SIZE, Canvas.CELL_SIZE);
console.log("draw " + image[1] + 'done');
}
}
}
}
}
And then, after move one piece, I draw board again by call :
ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);// clear all canvas
board.drawBlankBoard(); // redraw blank board - This working
board.drawPieces(); // redraw piece image - this NOT working
I have 2 question:
How to redraw same image (solve my problem) ?
What solution can improve performance rather than my current one ?
Thank for help !!!
Upvotes: 2
Views: 356
Reputation: 54026
The onload
callback will not fire again once the image has loaded unless you change the src
Change the function to what is in the snippet below.
You have used some old school patterns, some pointers regarding your code
for of
. Don't use for in
str[idx]
rather than str.charAt(idx)
String.slice
rather than String.subString
const ctx = this.canvas.getContext('2d'); // do once
drawPieces() {
const C_SIZE = Canvas.CELL_SIZE;
const status = this.boardStatus.split("_");
for (const image of Object.values(this.images)) {
for (const pieceOnBoard of status) {
if (image[0] === pieceOnBoard.slice(2)) {
const x = pieceOnBoard[0] * (C_SIZE + 1) + 1;
const y = pieceOnBoard[1] * (C_SIZE + 1) + 1;
ctx.drawImage(image[1], y, x, C_SIZE, C_SIZE);
}
}
}
},
Upvotes: 2