HTML5 Canvas performance very poor using rect()

前端 未结 1 1670
一整个雨季
一整个雨季 2020-12-11 21:40

I\'m writing a game, which displays the score at the top of the screen in the following fashion:

    canvasContext.fillStyle = \"#FCEB77\";
    canvasContext         


        
相关标签:
1条回答
  • 2020-12-11 22:21

    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.

    0 讨论(0)
提交回复
热议问题