且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

重绘 HTML5 画布非常慢

更新时间:2023-02-05 18:50:50

这里的代码做得更好.

http://jsfiddle.net/zHpgV/3/

以下是我更改的您应该考虑的事项的细分:

Here's a breakdown of the things that you should take into consideration that I changed:

  • 使用beginPath 连续添加到路径而不是停止并创建新路径.这是迄今为止最大的性能杀手.您最终会得到一条包含成千上万条线段的路径,这些线段永远不会被清除.
  • 在初始化时只需要创建一次时,会一遍又一遍地不断创建相同的路径.也就是说,您需要在 render 内部调用的唯一内容是 stroke.您不需要再次调用 lineTo/moveTo,当然也不会连续调用.见注释 1.
  • 为一条路径划过两次
  • 在 for 循环中抚摸
  • 重绘背景而不是设置 CSS 背景
  • 一遍又一遍地设置行帽
  • Continuous adding to a path instead of stopping and creating a new path with beginPath. This is by far the biggest performance killer here. You're ending up with a path with thousands and thousands of line segements that never gets cleared.
  • Continuously making the same path over and over when it only needs to be made once, on initialization. That is, the only thing you need to call inside of render is stroke. You do not need to call lineTo/moveTo ever again, and certainly not continuously. See note 1.
  • Stroking twice for one path
  • Stroking inside a for loop
  • Redrawing a background instead of setting CSS background
  • Setting the line cap over and over

注意 1: 如果您计划在您的应用程序中有多个路径,那么您可能应该缓存这样的路径,因为它们永远不会改变.我有关于如何做到这一点的教程这里.

Note 1: If you plan to have more than one path in your application then you should probably cache paths like this one since they never change. I have a a tutorial on how to do that here.

当然,如果您做这一切只是为了制作背景,则应将其另存为 png,并且您应该使用 CSS 背景图像.

像这样:http://jsfiddle.net/zHpgV/4/

然后突然你的渲染程序变得相当小:

Then suddenly your render routine is rather small:

function render() {
    c.clearRect(0, 0, scale, scale);
    c.fillText('{0}, {1}'.format(mouseX, mouseY), 0.5, 1.5);
}