Data URI leak in Safari (was: Memory Leak with HTML5 canvas)

前端 未结 4 2034
盖世英雄少女心
盖世英雄少女心 2020-12-08 16:11

I have created a webpage that receives base64 encoded bitmaps over a Websocket and then draws them to a canvas. It works perfectly. Except, the browser\'s (whether Firefox

4条回答
  •  时光说笑
    2020-12-08 16:47

    Without actual working code we can only speculate as to why.

    If you're sending the same image over and over you're making a new image every time. This is bad. You'd want to do something like this:

    var images = {}; // a map of all the images
    
    ws.onmessage = function(evt)
    {
        var received_msg = evt.data;
        var display_image;
        var src = 'data:image/bmp;base64,'+received_msg;
        // We've got two distinct scenarios here for images coming over the line:
        if (images[src] !== undefined) {
          // Image has come over before and therefore already been created,
          // so don't make a new one!
          display_image = images[src];
          display_image.onload = function () {
              context.drawImage(this, 0, 0);
          }
        } else {
          // Never before seen image, make a new Image()
          display_image = new Image();
          display_image.onload = function () {
              context.drawImage(this, 0, 0);
          }
          display_image.src = src;
          images[src] = display_image; // save it for reuse
        }
    }
    

    There are more efficient ways to write that (I'm duplicating onload code for instance, and I am not checking to see if an image is already complete). I'll leave those parts up to you though, you get the idea.

提交回复
热议问题