0

As seen from Stuck with SetInterval ,SetTimeOut and Requestanimationframe or the like, requestAnimationFrame repeat "once the browser is ready". In other words, it keeps the browser busy.

I'm creating a "hover" effect using "mousemove" when plotting a chart with many data points. It's easy to do by reploting the whole chart/canvas using requestAnimationFrame repeatedly. Code is short in this case.

Instead of the whole canvas, I tried to replot only the data point under mouse (hover, <1% of the canvas) using requestAnimationFrame. For that several arrays need to be added and the code is longer.

It can be different from case to case, but in general, is requestAnimationFrame a resource-intensive method? Redrawing the whole canvas for the sake of <1% of the area seems not sound economically.

Kaiido
  • 123,334
  • 13
  • 219
  • 285
weix
  • 1
  • 5

2 Answers2

0

requestAnimationFrame is not resource intensive, its purpose is to adjust the CPU consumption to what the screen can display (in terms of framerate).

You can assume that requestAnimationFrame allows your code to be ran once per frame of the screen. It's up to you to optimize the code of the callback so it doesn't recompute positions, shapes and colors of static things (only the point under the cursor).

Guerric P
  • 30,447
  • 6
  • 48
  • 86
0

Redrawing the whole canvas isn't the problem, the problem is redrawing the same image every frame.
Instead, redraw only when something has changed in your graphic.

You could start an infinite requestAnimationFrame (rAF) loop waiting for the state to change, but this will force the browser to stay in an animated mode, which forces it to enter some branches in the event-loop that it could otherwise ignore (specs). See this answer of mine for more details.

Given that mouse events are now throttled to screen refresh rate, in modern browsers you wouldn't even win by throttling this event in rAF, except that all the browsers still don't do that, looking at you Safari....

So to summarize,

  • Clear all / Redraw all. Painting only part of the canvas doesn't improve perfs that much, and this way you avoid a lot of trouble at coding.
  • Redraw only when your graphics changed. Avoid useless renderings.
  • Avoid keeping a requestAnimationFrame loop active for nothing. It just saves trees.
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • I added another eventListener to check whether the mouse is over the canvas. Otherwise it will not repeatedly redraw. I think this is what you suggested. Thanks. – weix Mar 22 '21 at 20:47
  • @weixwei not only no. I suggested you redraw only when something has changed (e.g when the mouse entered/exited your data points, and that you use rAF only to throttle the mouse event: don't make it an animation loop if there isn't an animation. – Kaiido Mar 22 '21 at 22:37
  • ok, that's a step further and it makes sense. – weix Mar 22 '21 at 22:45