Drawing images from a video stream

The drawImage(…) function can take a video element as its first parameter. The image that will be drawn is the one currently played by the video stream.

Online example at http://jsbin.com/dajena/3/edit

This example shows:

    • a <video> element on top, and four images drawn in a canvas below.
    • The images are drawn every XXX milliseconds using the setInterval(function, delay) method.
  1.    var video;
  2.    var canvas, ctx;
  3.    var angle = 0;
  4.  
  5. function init() {
  6.    video = document.getElementById(‘sourcevid’);
  7.    canvas = document.getElementById(‘myCanvas’);
  8.    ctx = canvas.getContext(‘2d’);
  9.  
  10.    setInterval(“processFrame()”, 25); // call processFrame each 25ms
  11. }
  12.  
  13. function processFrame() {
  14.     ctx.drawImage(video, 0, 0, 320, 180);

  15.     drawRotatingVideo(480, 90);

  16.     ctx.drawImage(video, 0, 180, 320, 180);
  17.     ctx.drawImage(video, 320, 180, 320, 180);
  18. }
  19.  
  20. function drawRotatingVideo(x, y) {
  21.      // Clear the zone at the top right quarter of the canvas
  22.     ctx.clearRect(320, 0, 320, 180);
  23.  
  24.     // We are going to change the coordinate system, save the context!
  25.     ctx.save();
  26.     // translate, rotate and recenter the image at its “real” center,
  27.     //not the top left corner
  28.     ctx.translate(x, y);
  29.     ctx.rotate(angle += 0.01); // rotate and increment the current angle
  30.     ctx.translate(-80, 45);
  31.  
  32.     ctx.drawImage(video, 0, 0, 160, 90);
  33.  
  34.     // restore the context
  35.     ctx.restore();
  36. }
  37. </head>
  38.  
  39. <body onload=init() >
  40. <p>This is a <video> element: </p>
  41. <video id=“sourcevid” autoplay=“true” loop=“true”>
  42. <sourcesrc=http://www.craftymind.com/factory/html5video/BigBuckBunny_640x360.mp4&#8221;
  43.          type=“video/mp4” />
  44. <sourcesrc=http://www.craftymind.com/factory/html5video/BigBuckBunny_640x360.ogv&#8221;
  45.          type=“video/ogg”/>
  46. </video>
  47. <p>This is a <canvas> element: </p>
  48. <canvas id=“myCanvas” width=“620” height=“360”></canvas>
  49. </body>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s