admin管理员组文章数量:1391969
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?
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?
Share Improve this question asked May 20, 2013 at 16:23 Paul MichaelsPaul Michaels 16.7k47 gold badges153 silver badges276 bronze badges1 Answer
Reset to default 9LIVE DEMO
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
is not really necessary in this case, but is there to illustrate the usage.
Try demo with and without the (begin/close)Path and pare the performance. I provided a rough fps counter but it is sufficient to see the decrease in performance.
You might need to check this on other browsers, including mobiles, so I set this JSPerf test.
本文标签: javascriptHTML5 Canvas performance very poor using rect()Stack Overflow
版权声明:本文标题:javascript - HTML5 Canvas performance very poor using rect() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744751802a2623225.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论