HTML5 Canvas performance very poor using rect()(使用 rect() 的 HTML5 Canvas 性能非常差)
问题描述
我正在编写一个游戏,它以以下方式在屏幕顶部显示分数:
I'm writing a game, which displays the score at the top of the screen in the following fashion:
canvasContext.fillStyle = "#FCEB77";
canvasContext.fillText(' Score: ' + Math.floor(score) + ' Lives: ' + Math.floor(lives) + ' other info: ' + Math.floor(otherInfo));
效果很好.然后我想做的是在该文本周围画一个框;所以我尝试了以下方法:
Which works fine. What I then wanted to do was to draw a box around that text; so I tried the following:
canvasContext.rect(2, 1, 210, 30);
canvasContext.rect(2, 1, 80, 30);
canvasContext.rect(80, 1, 70, 30);
canvasContext.strokeStyle = "#FCEB77";
canvasContext.stroke();
当我运行游戏时,性能的影响令人难以置信.我每帧都清除整个画布,但绘制三个矩形似乎会影响性能.谁能告诉我为什么,以及如何解决这个问题?
And when I ran the game the impact of performance was unbelievable. I'm clearing the entire canvas each frame, but drawing three rectangles seems to kill the performance. Can anyone tell me why, and how to get around this?
推荐答案
现场演示
尝试添加 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.
这篇关于使用 rect() 的 HTML5 Canvas 性能非常差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 rect() 的 HTML5 Canvas 性能非常差


- Fetch API 如何获取响应体? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01