javascripthtmlbrowserimagecreatefromjpg

How to embed mjpg streams with <img> tag without browser getting out of memory


The reason I'm using an <img> tag for the mjpg stream is that I'm able to size the image with css. However, after letting it run for a while, the browser crashes becuase it's getting out of memory.

I'm currently using URL.revokeObjectURL(mjpgURLwithOutdatedRandomParam) and add a new random param to the URL every few seconds. But unfortunately, the current Chrome still crashes with Out of Memory.

I also tried loading the stream into a canvas, but after a while the browser still gets out of memory:

const canvas = document.getElementById('canvas');
const image = new Image();

image.src = 'http://example.com';

const FRAME_RATE = 30;

image.onload = function() {
  canvas.width = image.width;
  canvas.height = image.height;

  setInterval(function() {
    const context = canvas.getContext('2d');
    context.drawImage(image, 0, 0, canvas.width, canvas.height);
  }, 1000 / FRAME_RATE);
};
<canvas id="canvas"></canvas>

What simple/optimal solution is there?

PS: I don't understand how a browser can support mjpg (within an <img> tag) but not be prepared to handle the memory...


Solution

  • This is because you are continuously drawing on the canvas. You need to clear the resources properly. See Example Below:

    const canvas = document.getElementById('canvas');
    const image = new Image();
    
    image.src = 'http://example.com';
    
    const FRAME_RATE = 30;
    
    image.onload = function() {
      canvas.width = image.width;
      canvas.height = image.height;
    
      setInterval(function() {
        const context = canvas.getContext('2d');
        
        // Clear the canvas before drawing each frame
        context.clearRect(0, 0, canvas.width, canvas.height);
        
        // Draw the image onto the canvas
        context.drawImage(image, 0, 0, canvas.width, canvas.height);
      }, 1000 / FRAME_RATE);
    };