javascript - HTML Canvas - too many rectangles break page -


my page breaks (chrome oops page) when try draw large number (+5000) of rectangles on canvas using:

rectangle:

ctx.rect(x,y,options.misssize,options.misssize); ctx.stroke(); 



however, page not break if draw same number of circles, triangles or x's using of 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 rect cause page crash, when none of other draw functions have issues?

i'm posting comment answer, seems have proved solution:

note how circle , triangle examples start beginpath, while rect example not!

here's mdn docs on canvas' 2d rendering context. note .rect() creates new path, while .stroke strokes every path:

canvasrenderingcontext2d.stroke(): strokes subpaths current stroke style.

in example you've been creating new path every new rectangle, , issuing new stroke command after each, meaning stroke command had more , more subpaths stroke every iteration, hence performance hit.


Comments