html - Canvas 消耗大量内存

标签 html google-chrome memory-leaks canvas html5-canvas

我在使用叠加层打开的 Canvas 实现时遇到困难。 canvas 元素宽 760px,高 2640px(我知道,别问)。

我在每 27.5 像素高处绘制线条。

ctx.moveTo(0, y);
ctx.lineTo(760, y);
ctx.strokeStyle = 'rgb(100,100,100)';
ctx.stroke();

显然,在创建 Canvas 时,浏览器似乎对此“感到窒息”。最终它通过(1-5 秒)并且内存增加了 20MB。

关闭叠加层似乎并不能释放此内存。 当我重新打开叠加层(重新绘制 Canvas )时,内存再次增加。 等等等等... 通过这种方式,我的 chrome 进程很快就从 60MB 内存增加到 600+。

将 Canvas 的大小调整为 264 像素高并每 2.75 像素绘制线条速度更快并且只消耗大约 4MB(当然这似乎也没有被清除)。

谁有一些关于如何避免这种情况的指示。


这是更多代码 data 是一个包含 Entries 属性的对象数组,该属性也是一个数组。

[ { Entries : [{...},{...},...] }, {...}, ... ]

var $canvas = container.find('canvas')
    , canvas = $canvas.get(0)
    , maxY = canvas.height
    , maxX = canvas.width
    , dX = maxX / (data.length + 1)
    , ctx = canvas.getContext('2d');


var x1, y1, y2, mh;

$.each(data, function (i, day) {
    if (!day.Entries) return;

     $.each(day.Entries, function (j, entry) {
         x1 = (i + 1) * dX;
         mh = entry.BeginDate.toHourMinutes();
         y1 = (((mh.h * 60) + mh.m) / 1440) * maxY;
         mh = entry.EndDate.toHourMinutes();
         y2 = (((mh.h * 60) + mh.m) / 1440) * maxY;

         switch (entry.Type) {
             case CALENDARTYPES.OPENINGHOUR:
                 ctx.beginPath();
                 ctx.rect(x1, y1, dX - 10, y2 - y1);
                 ctx.fillStyle = "rgb(125, 125, 125)";
                 ctx.fill();
                 ctx.closePath();
                 break;
             case CALENDARTYPES.BLOCKING:
                 ctx.clearRect(x1, y1, dX, y2 - y1);
                 break;
         };
      });
  });

       delete x1, y1, y2, mh;

       //Draw grid on canvas.

       var x = 0
           , y = +0.5
           , stepYH = maxY / 24
           , stepYQ = stepYH / 4
           , isHour = true;

       ctx.lineWidth = 1;

       while (y < maxY) {
           isHour = (((y - 0.5) % stepYH) == 0);
           ctx.moveTo(isHour ? x : x + dX, y);
           ctx.lineTo(maxX, y);
           ctx.strokeStyle = isHour ? 'rgb(175,175,175)' : 'rgb(100,100,100)';
           ctx.stroke();
           y += stepYQ;
       };

最佳答案

根据评论:

如果你不清除路径,你基本上是在扩展路径,并且由于 .stroke() 绘制了(整个)路径,你最终会画得越来越多使用 .moveTo/.lineTo 添加更多点。

使用 .beginPath() 可能更有意义,这样您就可以只抚摸新路径而不抚摸旧路径:

  • 从内存中清除路径 - 减少泄漏
  • 不再绘制旧路径 - 减少性能损失

关于html - Canvas 消耗大量内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7658523/

相关文章:

html - 链接垂直对齐问题

javascript - 通过单选按钮隐藏/显示 div

javascript - 每 2 秒重新加载一个 div 并发布数据

javascript - 对象和 console.log 的奇怪行为

javascript - 谷歌浏览器中的Webgl着色器编译错误

python - 如何查找 <div > 的特定属性的值

javascript - 用于记录和播放窗口事件的 chrome 扩展

android - 如何修复 Android 中有关数组数组的内存泄漏?

java - Android 资源中的图像导致内存泄漏

c++ - 内存泄漏检测和覆盖新功能?