Motion jpeg in html5 canvas

clwen picture clwen · Nov 21, 2012 · Viewed 27.1k times · Source

I'm trying to wrap motion jpeg (mjpeg) stream (from webcam) into html5 canvas. I know Safari and Chrome have native support for mjpeg so that I can put it into img to make it work. The reason I want to wrap it in canvas is that I want to do some post processing on it.

I know i can use drawImage to load an image (and mjpeg):

<html>
  <body>
    <canvas id='test_canvas' width='640px' height='480px' style='border:1px solid #d3d3d3'>
    </canvas>
    <script language="JavaScript">
      var ctx = document.getElementById('test_canvas').getContext('2d');
      var img = new Image();
      img.onload = function() {
        ctx.drawImage(img, 0, 0);
      };
      var theDate = new Date();
      img.src = "http://some.video.stream.edu/axis-cgi/mjpg/video.cgi?";
    </script>
  </body>
</html>

However, it load mjpeg as an image so only display the first frame. Put ctx.drawImage(img, 0, 0) into a while (true) loop also not help (not surprisingly).

I think there should be some tricks to make it work, still googling around, just not sure which direction is more promising. It is OK to be only supported by some reasonably modern browsers.

Answer

Fredrik picture Fredrik · Mar 31, 2013

Another solution is to add this in you javascript.

window.setInterval("refreshCanvas()", 10);
function refreshCanvas(){
  ctx.drawImage(img, 0, 0);
};

It will redraw the image in the Canvas every 10 ms.

BR / Fredrik