且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 rect() 的 HTML5 Canvas 性能非常差

更新时间:2021-08-22 21:06:32

现场演示

尝试添加 beginPath 方法,如下代码:

Try add the beginPath method, like the following code:

canvasContext.beginPath();
canvasContext.rect(2, 1, 210, 30);
canvasContext.rect(2, 1, 80, 30);
canvasContext.rect(80, 1, 70, 30);
canvasContext.strokeStyle = "#FCEB77";
canvasContext.stroke();
canvasContext.closePath();

使用路径绘图时,您使用的是虚拟笔"或指针".如果没有路径,将导致画布状态机直接更改,从而使事情变慢.

When drawing using a path, you are using a virtual "pen" or "pointer". Without the path, will cause direct changes on canvas state machine which make things slow.

closePath 在这种情况下并不是真正需要的,但可以用来说明用法.

closePath is not really necessary in this case, but is there to illustrate the usage.

尝试 demo 使用和不使用 (begin/close)Path 并比较性能.我提供了一个粗略的 fps 计数器,但足以看到性能下降.

Try demo with and without the (begin/close)Path and compare the performance. I provided a rough fps counter but it is sufficient to see the decrease in performance.

您可能需要在其他浏览器(包括手机)上进行检查,因此我设置了此 JSPerf 测试.

You might need to check this on other browsers, including mobiles, so I set this JSPerf test.