I made a platformer using ctx.clearRect and ctx.fillRect, so each time the player moved I would just delete the previous position and draw him again.

Now I'm working on importing my own art into the game and I'm having problems removing the previously drawn image.

Example of some of the code I am using now to render the player:

var playerReady = false;
var playerImage = new Image();
playerImage.onload = function () {
    playerReady = true;
playerImage.src = "images/player.png";

var render = function () {
    if (playerReady) {
        ctx.drawImage(playerImage, player.x, player.y);

So Im wondering if there is anything similar to ctx.clearRect for ctx.drawImage or what I could do, my current workaround is to render the whole background on top of the previously drawn background + player but this is not ideal for what I´m trying to do.

thank you!


1 Answer 1


The HTML5 canvas works... well... like a canvas. It is a collection of RGBA pixels. When you draw something, it replaces whatever was there before. There is no "undo" functionality.

The usual approach is what you are doing right now: start each rendering frame by completely erasing the canvas and redrawing the whole scene from scratch.

When you have lots of static content which doesn't change per frame, some dynamic objects which move and performance is really a concern, you can also layer canvases. Create multiple <canvas>es and move them on top of each other using CSS positioning. That way you can work with each canvas separately without destroying the content of the others. Use the lower canvas for static content which is never erased and the upper canvas for any dynamic content which is erased and redrawn every frame.

Another more old-school trick is using dirty rectangles: In your logic loop, mark rectangular areas of the screen which need to be redrawn because their content changed. In your rendering loop, only draw the areas which are marked as dirty. This isn't easy to implement and will make your whole engine a lot more complex, but it can really improve graphic performance a lot when most parts of your screen don't change often and you implement it correctly.

  • \$\begingroup\$ Great, thank you so much for the answer! I thought I was doing something wrong by redrawing the background, also great to hear about the other options I have with multiple canvas and dirty rectangles, will look those up if the need arises! \$\endgroup\$
    – Ommi
    Aug 11, 2014 at 11:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .