Chris
Chris

Reputation: 27384

HTML5 Canvas animation issue

I am experimenting with HTML5 Canvases in an attempt to create some animation. My ultimate goal is to be able to animate a box to a particular location at whim, for now im just animating it across the screen. When I move it across the screen I geta black trail left behind, how do I clear this "dirty" section without removing the background grid?

A jsFiddle of the code is here

Upvotes: 1

Views: 359

Answers (2)

Nikola Radosavljević
Nikola Radosavljević

Reputation: 6911

You have to clear what you've drawn if you don't want it to be visible. I assume you don't want to clear entire canvas to avoid redrawing grid and spending CPU cycles. You'll have to do this differently.

Possible solutions:

  • have two same onscreen canvases one over the other. Draw grid on canvas below and don't clear it. Clear part of top canvas and redraw on it.
  • have one on-screen and one off-screen canvas. Draw grid on off-screen canvas. Each time you animate, clear whole on-screen canvas, copy prepared grid from other one, and draw what you need over it.

Upvotes: 1

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83358

Two solutions

  • Redraw the background on the top of animation before moving it to the new location. This so called dirty sprite technique - faster - more complex.

  • Redraw the whole canvas between frames

If drawing the background is a complex operation just hold a prepared background buffered in another canvas for speed.

Upvotes: 3

Related Questions