简体   繁体   中英

JavaScript base64 image source memory management in an html5 canvas application

Lets get right to the code:

function drawImg(img) {                       
    var image = new Image();
    image.onload = function() {                                     
        context.drawImage(image, 0, 0);
    }; 
    image.src = img; 
}; 

This is a pretty common basic implementation of drawing an image to an html5 canvas context.

The value passed to the drawImg function: img, is a base64 string like

"data:image/png;base64,somebase64stuffhere...."

Now let us say that drawImg is being called 15 times per second (15fps) and that the size of the base64 encoded img is 20-30k.

FireFox and Internet Explorer's 10,11 perform well enough. GC and memory spiking on FF get a little wild but it's within acceptable ranges. Earlier versions of IE, and most depressingly, chrome, fail to manage the memory allocation of, assuming, the Image object, and in short order will consume all the memory available and crash.

  • I've commented out the canvas portion of this code.
  • I've commented out the entire section of code to check against memory leaks outside of the drawImg function.
  • My conclusion is that, the image, image.onload, image.src code bits are causing the crashing memory growth.
  • Similar questions here on SO confirm this thought, however I haven't been able to validate any of the solutions for my particular case.

So my question: How can I best implement this without running up memory in some browsers?

Caveats:

  • I'd prefer not to stray to far from the concept of getting a base64 string, at no point am I writing to a filesystem and prefer to keep it that way.
  • I do not have the liberty of simply refreshing the page.

It seem to be a know issue in Chrome:

https://code.google.com/p/chromium/issues/detail?id=309543

There'll still be growth observed in the TC, but most of that should be due to GC heuristics, so will be collected eventually, keeping memory usage bounded.

And as of Jan 21:

Latest dev should have it [fix] by now. (34.0.1788.0 I think)

Version 34 is currently Canary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM