Canvas animation frame rendering: Infinite Loop vs

2019-08-29 07:52发布

问题:

Ok, this is very theoretical question: I am coding an animation with the HTML5 canvas element. The animation is dependent on the mouse moving (when mouse rests = no animation). For the rendering, I see the following options:

  • Option 1: A loop that keeps constantly redrawing the canvas (wether the mouse is moving or not)
  • Option 2:Triggering the draw function through the mousemove() event (using jQuery)

I tend to favor option 2, because the rendering is only proccessed when needed. But I am worried about about one thing: If the mouse moves too fast (and especially on slower machines), the iterations might overlap and mess up the canvas (see my illustration below).

So I thought about a workaround:

  • Option 3: Using option 2, but checking on each trigger if there is already a draw iteration being currently executed. If yes, the trigger is ignored.

But I can see a few problems here too: As in my illustration, the last frame of a mouse move might be left out (because it overlaps a previous call). Plus, the constant checking might dicrease performance (which is not needed in option 1).

So which one of the options is the best? Does anybody have some experience on this?

Link to the illustration (can't post images yet): http://i.stack.imgur.com/WHLDQ.png

回答1:

I use a combination of both.

I have 2 global variables (mousex,mousey) I update these on mousemove

And i have a draw loop that start on load and repeast every ,n-seconds

Edit: the idea is to split the visual and the working code (collision,score,...)

The drawing loop fires every 2 sec while the mousemove is updated on everymove

-the loop is that set so slow becaus it show the diffrence example : jsfiddle.net/9jW3d/show/``



回答2:

I'd go for option 2. Option 1 is just waste of resources. Don't worry about option 2 overlapping iterations. The DOM doesn't call a mousemove event when the previous one is still running.