我在使用覆盖层打开的 Canvas 实现时遇到困难。
canvas 元素宽 760px,高 2640px(我知道,别问)。
我每隔 27.5 像素高画一条线。
ctx.moveTo(0, y);
ctx.lineTo(760, y);
ctx.strokeStyle = 'rgb(100,100,100)';
ctx.stroke();
显然,在创建画布时,浏览器似乎对此感到“窒息”。最终它完成了(1-5 秒)并且内存增加了 20MB。
关闭覆盖似乎并没有释放该内存。
当我重新打开覆盖层(重新绘制画布)时,内存再次增加。
等等等等...
我的 chrome 进程很快就从 60MB 内存增加到了 600+。
将画布大小调整为 264 像素高并每 2.75 像素绘制线条速度更快,并且仅消耗约 4MB(当然这似乎也没有被清除)。
谁有一些关于如何避免这种情况的指示。
Here is more code
data is an array of objects containing an Entries property which is also an array.
[ { 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;
};