2011-02-03 106 views
3

我用“画布”元素的工作,并试图做的Javascript图像的一些基于像素的操作在Firefox 4什么正在泄漏内存与这种使用getImageData,javascript中,HTML5画布

下面的代码泄漏内存,我想知道是否有人可以帮助识别泄漏。

所使用的图像被预加载,并且这些代码片段一旦被加载就被调用(进入pImages数组)。

var canvas = document.getElementById('displaycanvas'); 
    if (canvas.getContext){ 
     var canvasContext = canvas.getContext("2d"); 
     var canvasWidth = parseInt(canvas.getAttribute("width")); 
     var canvasHeight = parseInt(canvas.getAttribute("height")); 

     // fill the canvas context with white (only at start) 
     canvasContext.fillStyle = "rgb(255,255,255)"; 
     canvasContext.fillRect(0, 0, canvasWidth, canvasHeight); 

     // for image choice 
     var photoIndex; 

     // all images are the same width and height 
     var imgWidth = pImages[0].width; 
     var imgHeight = pImages[0].height; 

     // destination coords 
     var destX, destY; 

     // prep some canvases and contexts 
     var imageMatrixCanvas    = document.createElement("canvas"); 
     var imageMatrixCanvasContext  = imageMatrixCanvas.getContext("2d"); 


     // Set the temp canvases to same size - apparently this needs to happen according 
     // to one comment in an example - possibly to initialise the canvas? 
     imageMatrixCanvas.width   = imgWidth; 
     imageMatrixCanvas.height  = imgHeight; 

     setInterval(function() { 
      // pick an image 
      photoIndex = Math.floor(Math.random() * 5); 

      // fill contexts with random image 
      imageMatrixCanvasContext.drawImage(pImages[photoIndex],0,0); 
      imageMatrixData = imageMatrixCanvasContext.getImageData(0,0, imgWidth, imgHeight); 

      // do some pixel manipulation 
      // ... 
      // ... 

      // choose random destination coords (inside canvas) 
      destX = Math.floor(Math.random() * (canvasWidth - imgWidth)); 
      destY = Math.floor(Math.random() * (canvasHeight - imgHeight)); 

      // show the work on the image at the random coords 
      canvasContext.putImageData(imageMatrixData, destX, destY); 
     }, 500);   
    } 
+2

什么浏览器? IE浏览器?你怎么知道它正在泄漏内存? – 2011-02-03 22:17:43

+0

@MattBall - 我发现它不是浏览器 - afaik,它是DOM和Javascript内存之间的桥梁。看到我对下面的Martin Jespersen的回应。 – stephendwolff 2011-04-18 12:47:42

回答

0

更改imageMatrixData = ...var imageMatrixData = ...可能有点帮助,但我怀疑这是完整的故事。但据我可以告诉imageMatrixData是您在每一个区间反复分配一个全球范围内的变量,并不能成为健康尤其是数据:)

我知道getImageData使用Chrome浏览器memoryleak但一大块是在版本7之前,不知道现在是怎么回事,并且看到你在谈论ff4时,那么这可能是非常不相关的。

+1

感谢您的意见马丁。我发现主要问题是在循环内部使用getImageData(setInterval)。据我可以收集 - 以前的使用没有正确处理 - 我认为它是类似于我读过的IE浏览器的JavaScript内存泄漏 - 穿越DOM/JavaScript鸿沟时。只要我在循环之外完成所有getImageData(即准备中),内存似乎不会泄漏。这就是说 - 铬使用更少的内存来完成同样的任务... – stephendwolff 2011-02-05 21:52:45

1

哦..错误。内存在几次测试后看起来没问题。
但还有另一个问题。
使用的内存由制表工艺的尺寸变化IMG元素的src属性,当越来越多......

Src property = canvas.getContext('2d').toDataURL('image/png') (changing each time); 

我试图“删除img.src”,删除节点...