Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

javascript - HTML5 Canvas performance very poor using rect()

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

LIVE 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 compare 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...