javascript - 如何优化 JS canvas 绘图?

标签 javascript html canvas

我对 fillRect 的实现比 context2d.fillRect 慢很多(> 3 倍)。我如何优化我的代码或为什么内置 fillRect 更快(一些应用程序加速?)?

我的建议:

  __fillRect : function (data, x, y)//, r, g, b)
  {
    var w = this.__width * 4;
    var idx = x * 4+ y * w;
    var idx_1 = idx + 4;
    var idx_2 = idx + 8;
    var idx_3 = idx + w;
    var idx_4 = idx_3 + 4;
    var idx_5 = idx_3 + 8;
    var idx_6 = idx_3 + w;
    var idx_7 = idx_6 + 4;
    var idx_8 = idx_6 + 8;

    function __setPixelIdx (idx)
    {
      data[idx + 0] = 200;
      data[idx + 1] = 0;
      data[idx + 2] = 0;
      data[idx + 3] = 255;
    }

    __setPixelIdx (idx);
    __setPixelIdx (idx_1);
    __setPixelIdx (idx_2);
    __setPixelIdx (idx_3);
    __setPixelIdx (idx_4);
    __setPixelIdx (idx_5);
    __setPixelIdx (idx_6);
    __setPixelIdx (idx_7);
    __setPixelIdx (idx_8);

  },

最佳答案

由于以下几个原因,您的实现速度较慢:

  • 您正在写入一个数组,然后将其复制并转换到 Canvas 帧缓冲区中。
  • context2d.fillRect 正在运行 native 代码,而不是解释或 JIT 编译的 JavaScript。
  • context2d 可能会使用图形硬件来绘制
  • 您一次写入单个字节,而即使是未加速的 native 库也可以写入整个 int32 像素值

我的建议是使用原生的 fillRect 方法,除非你有很好的理由不这样做(例如,自己做阴影或 mask )。您将无法接近库函数的速度。

在主 __fillRect 函数中调用 __setPixelIdx 而不是访问 data 可能没有太大帮助。

关于javascript - 如何优化 JS canvas 绘图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3297680/

相关文章:

javascript - HTML Canvas 通过鼠标平移

javascript - 使用 javascript 将响应式语音气泡添加到 Canvas

javascript - 提交多个表单后重定向

jquery - 想要将点击转换为悬停 jquery 自动完成

javascript - 在 JavaScript 中清空节点的最佳方法是什么

html - 如何使用 CSS 将文本环绕在图像周围?

html - IE 中的关键帧背景动画有一些问题

java - Canvas SWT Draw2D 上的圆柱体图形

javascript - 点击下载按钮直接下载图片

javascript - D3 可重复使用的圆形热图无法成功更新