开发者

Freeing ImageData when deleting a Canvas

I'm writing a XUL application using HTML Canvas to display Bitmap images. I'm generating ImageDatas and importing them in a canvas using the putImageData function :

  for(var pageIndex=0;pageIndex<100;pageIndex++){
   this.img = imageDatas[pageIndex];

   /* Create the Canvas element */
   let imgCanvasTmp = document.createElementNS("http://www.w3.org/1999/xhtml",'html:canvas');
   imgCanvasTmp.setAttribute('width', this.img.width);
   imgCanvasTmp.setAttribute('height', this.img.height);

   /* Import the image into the Canvas */
   imgCanvasTmp.getContext('2d').putImageData(this.img, 0, 0);

   /* Use the Canvas into another part of the program (Commented out for testing) */
  // this.displayCanvas(imgCanvasTmp,pageIndex);
  }

The images are well imported but there seems to be a memory leak due to the putImageData function.

When exiting the "for" loop, I would expect the memory allocated for the Canvas to be freed but, by executing the code without executing putImageData, I noticed that my program at the end uses 100Mb less (my images are quite big).

I came to the conclusion that the putImageData function prevents the开发者_如何学运维 garbage collector freeing the allocated memory.

Do you have any idea how I could force the garbage collector to free the memory? Is there any way to empty the Canvas?

I already tried to delete the canvas using the delete operator or to use the clearRect function but it did nothing.

I also tried to reuse the same canvas to display the image at each iteration but the amount of memory used did not changed, as if the image where imported without deleting the existing ones...


You could try clearing the canvas after the loop. Looking at your code, imgCanvasTmp is still reachable, and can't be garbage collected. Note that you might need to let the browser idle for a few minutes before the garbage collector to kick in. Also, maybe you want to clear imageDatas too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜