简体   繁体   English

HTML画布-太多矩形中断页面

[英]HTML Canvas - too many rectangles break page

My page breaks (chrome oops page) when I try to draw a large number (+5000) of rectangles on my canvas using: 当我尝试使用以下方法在画布上绘制大量(+5000)矩形时,页面破裂(chrome oops页面)

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: 但是,如果使用以下任意一种绘制相同数量的圆,三角形或X,则页面不会中断:



circle : 圈子

ctx.beginPath();
ctx.arc(x,y,options.missSize/2,0,2*Math.PI);
ctx.stroke();

X : 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? 当其他绘制函数都没有任何问题时,为什么rect会导致我的页面崩溃?

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! 请注意,您的圆形和三角形示例如何以beginPath ,而rect示例则不是!

Here's the MDN docs on canvas' 2D rendering context. 这是画布的2D渲染上下文上的MDN文档。 Note that .rect() creates a new path, while .stroke strokes every path : 请注意, .rect()创建一个新路径,而.stroke抚摸每个路径

CanvasRenderingContext2D.stroke() : Strokes the subpaths with the current stroke style. CanvasRenderingContext2D.stroke() :以当前笔触样式笔触子路径。

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. 在您的示例中,您已经为每个新矩形创建了新路径,并在每个矩形后发出了新的stroke命令,这意味着您的stroke命令在每次迭代中都有越来越多的子路径来描边,因此会降低性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM