arasteveg
arasteveg

Reputation: 41

Move image in <canvas> without redrawing entire canvas?

I've made a game board and I want to drag and drop my pieces (.gif's) but I can't find a way to do this without having to redraw the entire board endlessly since I have to clear the piece every time it moves 1 pixel and that clears whatever was under it too (the board and other pieces). Is it even possible?

Upvotes: 4

Views: 2303

Answers (1)

robbrit
robbrit

Reputation: 17960

Yes, you do need to redraw the entire board each time.

One technique you can use is an offscreen canvas:

var board = document.createElement("canvas");
board.width = width;
board.height = height;

var boardContext = board.getContext("2d");

// rendering code for board
// ...

// now draw board onto main canvas
var context = mainCanvas.getContext("2d");

context.drawImage(board, ...);

The board canvas is not visible on the screen, but it will be stored in memory so that each time you need to re-render, it renders very quickly.

Upvotes: 7

Related Questions