Puskin
Puskin

Reputation: 157

Redraw same image on canvas

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:

  1. How to redraw same image (solve my problem) ?

  2. What solution can improve performance rather than my current one ?

Thank for help !!!

Upvotes: 2

Views: 356

Answers (1)

Blindman67
Blindman67

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

Snippet

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

Related Questions