【问题标题】:Huge memory leak in javascriptjavascript中的巨大内存泄漏
【发布时间】:2016-05-24 19:38:33
【问题描述】:

我正在处理一个画布元素,我想我会添加一些简单的图形元素,但由于某种原因,它们使 fps 停止运行。没有它们它是 60 fps,有它们它在运行后一分钟内会减慢到 3-4 fps:

ctx.rect(0, 0, cnv.width, cnv.height);
ctx.fillStyle = ctx.createPattern(albImg[8], "repeat");
ctx.fill();

ctx.lineWidth="1";
ctx.strokeStyle="#5d92de";
ctx.rect(173.5,638.5,623,98);
ctx.stroke();

我做错了什么?

【问题讨论】:

  • albImg[8]的图像属性是什么?很大吗?
  • 你为什么要每帧创建一个新模式?这不可能很快。
  • 是的,你是对的,我可能应该在单独的上下文中执行该模式,然后使用该 Ssube:不,它是一个小图标 - 358 字节。奇怪的是,即使我注释掉了前 3 行,它仍然会因为剩下的 4 行而停止——它只需要更长的时间,这真的很奇怪。删除所有 7 行后,画布的其余部分可以正常运行数小时而 fps 没有下降。
  • 好的,所以我发现了最后几行的问题:我使用的是 ctx.stroke 而不是 strokeRect。有背景的第一部分对我来说仍然是个谜,即使我在循环之外定义它仍然无法正常工作。 [代码]var muhpatturn = ctx.createPattern(albImg[8], "repeat");功能 mechbay(){ ctx.rect(0, 0, cnv.width, cnv.height); ctx.fillStyle = muhpatturn; ctx.fill(); ctx.lineWidth=1; ctx.strokeStyle='#5d92de'; ctx.strokeRect(173.5,638.5,623,98); [/code]
  • @DanielBengtsson,是的,正如您所发现的,使用 strokeRect。或者,您可以在ctx.rect 之前添加ctx.beginPath。发生的情况是,自上次 beginPath 以来,所有先前的矩形都被重新绘制,因此您在制作动画时确实绘制了数百个矩形。

标签: javascript canvas memory memory-leaks


【解决方案1】:

动画会随着每个新的动画循环而变慢

@DanielBengtsson,是的,正如您所发现的,使用 strokeRect。

或者,您可以在 ctx.rect 之前添加 ctx.beginPath。发生的情况是,自上次 beginPath 以来所有先前的矩形都被重新绘制,因此您在制作动画时确实绘制了数百个矩形。

// alternative with beginPath so previous rects will not redraw and
//     cause slowdowns.
ctx.lineWidth="1";
ctx.strokeStyle="#5d92de";
ctx.beginPath();
ctx.rect(173.5,638.5,623,98);
ctx.stroke();

重复背景图案 - 等待图像完全加载后再尝试使用它

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;

var img = new Image();
img.onload = start;
img.src = "https://dl.dropboxusercontent.com/u/139992952/multple/emoticon1.png";

function start() {
  ctx.fillStyle = ctx.createPattern(img, "repeat");
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>

【讨论】:

    猜你喜欢
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2014-02-10
    • 2013-05-15
    • 1970-01-01
    相关资源
    最近更新 更多