Reputation: 3763
My page breaks (chrome oops page) when I try to draw a large number (+5000) of rectangles on my canvas using:
rectangle:
ctx.rect(x,y,options.missSize,options.missSize);
ctx.stroke();
However, my page does not break if I draw the same number of circles, triangles or X's using any of the following:
circle:
ctx.beginPath();
ctx.arc(x,y,options.missSize/2,0,2*Math.PI);
ctx.stroke();
X:
ctx.beginPath();
ctx.moveTo(x - options.missSize/2, y - options.missSize/2);
ctx.lineTo(x + options.missSize/2, y + options.missSize/2);
ctx.stroke();
ctx.moveTo(x + options.missSize/2, y - options.missSize/2);
ctx.lineTo(x - options.missSize/2, y + options.missSize/2);
ctx.stroke();
triangle:
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x+(options.missSize/2), y+options.missSize);
ctx.lineTo(x-(options.missSize/2), y+options.missSize);
ctx.lineTo(x, y);
ctx.stroke();
Why would rect
cause my page to crash, when none of the other draw functions have any issues?
Upvotes: 1
Views: 177
Reputation: 4506
I'm posting my comment as an answer, as it seems to have proved a solution:
Note how your circle and triangle examples start with beginPath
, while your rect example does not!
Here's the MDN docs on canvas' 2D rendering context. Note that .rect()
creates a new path, while .stroke
strokes every path:
CanvasRenderingContext2D.stroke(): Strokes the subpaths with the current stroke style.
In your example you've been creating a new path for every new rectangle, and issuing a new stroke command after each, meaning your stroke
command had more and more subpaths to stroke every iteration, hence the performance hit.
Upvotes: 1