Does the canvas change every time something changes?

I did some research on how the canvas works. This “immediate mode” is supposed to mean that he doesn’t remember what his drawing looks like, only the bitmap remains with every change.

This seems to suggest that the canvas is not redrawn on change.
However, when I tested the canvas on the iPad (mostly I continue to draw parallel lines on the canvas), the frame rate decreases rapidly when there are more lines on the canvas. Lines stretch more slowly and more nervously.

Does this mean that the canvas should actually paint everything about the changes? Or is there another reason for this performance change?

+7
source share
1 answer

The HTML canvas remembers the final state of the pixels after each stroke / fill call. He never redraws. (The web browser may need to re-split parts of the final image on the screen, for example, if another HTML object is moved around the canvas and then deleted again, but this is not the same as re-issuing drawing commands.

The context always remembers its current state, including any path that you have accumulated. You probably (accidentally) do not clear your path between "updates", etc. On the first frame you draw one line, on the second frame two lines, on the third frame three lines, etc. (Do you call ctx.closePath() and ctx.beginPath() ? Do you clear the canvas between the pictures?)

Here's an example showing that the canvas is not redrawing itself. Even in tens of thousands of lines, I see the same frame rate as hundreds of lines (at 200 frames per second on Chrome, ~ 240 frames per second on Firefox 8.0, when drawing 10 lines per frame).

 var lastFrame = new Date, avgFrameMS=5, lines=0; function drawLine(){ ctx.beginPath(); ctx.moveTo(Math.random()*w,Math.random()*h); ctx.lineTo(Math.random()*w,Math.random()*h); ctx.closePath(); ctx.stroke(); var now = new Date; var frameTime = now - lastFrame; avgFrameMS += (frameTime-avgFrameMS)/20; lastFrame = now; setTimeout(drawLine,1); lines++; } drawLine(); // Show the stats infrequently setInterval(function(){ fps.innerHTML = (1000/avgFrameMS).toFixed(1); l.innerHTML = lines; },1000); 

In action: http://phrogz.net/tmp/canvas_refresh_rate.html

For more information on what your code is really doing compared to what you suspect it is doing, share your test case with us.

+11
source

All Articles