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 性能非常差
				
        
 
            
        基础教程推荐
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
 - 什么是不使用 jQuery 的经验技术原因? 2022-01-01
 - 每次设置弹出窗口的焦点 2022-01-01
 - jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
 - WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
 - Node.js 有没有好的索引/搜索引擎? 2022-01-01
 - 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
 - 如何在特定日期之前获取消息? 2022-01-01
 - Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
 - 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				