画布的JavaScript内存问题 [英] JavaScript memory problem with canvas

查看:87
本文介绍了画布的JavaScript内存问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HTML5画布上使用 getImageData / putImageData 以便能够操作图片。
我的问题是浏览器似乎永远不会释放任何内存。直到我关闭标签(在Chrome和Opera中测试)。

I'm using getImageData/putImageData on a HTML5 canvas to be able to manipulate a picture. My problem is that the browser never seems to free any memory. Not until I close the tab (tested in Chrome and Opera).

将这些移出功能:

Moved these out of the function:


 var ctx = document.getElementById('leif').getContext('2d');
 var imgd = ctx.getImageData(0,0,width,height);
 var pix = imgd.data;
 var rndpixel = 0;

并且问题消失了!

function infiniteLeif()
{
  for (var i = 0; i<65536; i+=4) {
    rndpixel=Math.floor(Math.random()*(width*(height-2))+width+4) * 4;
    pix[rndpixel-wx4] = pix[rndpixel]; pix[rndpixel-wx4+1] = pix[rndpixel+1]; pix[rndpixel-wx4+2] = pix[rndpixel+2];
    pix[rndpixel+wx4] = pix[rndpixel]; pix[rndpixel+wx4+1] = pix[rndpixel+1]; pix[rndpixel+wx4+2] = pix[rndpixel+2];
    pix[rndpixel-4] = pix[rndpixel]; pix[rndpixel-4+1] = pix[rndpixel+1]; pix[rndpixel-4+2] = pix[rndpixel+2];
    pix[rndpixel+4] = pix[rndpixel]; pix[rndpixel+4+1] = pix[rndpixel+1]; pix[rndpixel+4+2] = pix[rndpixel+2];
  }

  ctx.putImageData(imgd,0,0);
  if (go==1) t=setTimeout(infiniteLeif,40);
}

一个完整的示例可在此处找到(建议使用Google Chrome)。

A full example can be found here (Google Chrome is recommended).

这不是 setTimeout 这是问题,因为我尝试了一个具有相同效果的循环。

It's not the setTimeout that is the problem because I tried a loop with the same effect.

我已经明白删除了循环引用通常是关键,但我真的有一个吗?如何更改此代码,以便 JavaScript GC 有机会完成它的工作?

I've come to understand that removal of circular references often is the key but do I really have one? How can I change this code so that the JavaScript GC gets a chance to do it's job?

推荐答案

它可能没有帮助,可能是你的泄漏,但是你每隔40ms重新加载一个数据,但数据还没有t改变了。

It won't help, possibly with your leak, but you are reloading an array every 40ms with data that hasn't changed.

您可能希望在初始化时使用闭包。

You may want to use a closure around the initialization.

基本上,只需创建一个变量它具有循环功能,其中包含像素信息。

Basically, just create a variable that has the function with the loop, with the pix info enclosed within it.

然后,您只需继续递归调用不重新初始化的位置,但只需使用循环变量。

Then, you just continue to recursively call where you don't reinitialize, but just use the variable with the loop.

这样你重复使用相同的像素信息,它保持状态,这应该没问题,除非你在其他地方编辑画布。

This way you reuse the same pix info, it maintains it's state, which should be fine, unless you edit the canvas elsewhere.

这篇关于画布的JavaScript内存问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆