title: setting background image on canvas from web camera
body: <p>My goal is set Background image from web-camera. Every time i click on button, background image should change. I am drawing an image from web-camera in update function. But there is the problem. Background image is always changing. I have to draw this image in update function.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>window.onload = function() {
  
    backgroundImage = null;
  
    // Grab elements, create settings, etc.
    var video = document.getElementById('video');
  
    // Get access to the camera!
    if (navigator.mediaDevices &amp;&amp; navigator.mediaDevices.getUserMedia) {
      // Not adding `{ audio: true }` since we only want video now
      navigator.mediaDevices.getUserMedia({
        video: true
      }).then(function(stream) {
        video.src = window.URL.createObjectURL(stream);
        video.play();
      });
    }
  
    //get canvas and context element
    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
  
    // Trigger photo take
    document.getElementById("snap").addEventListener("click", function() {
      backgroundImage = video;
    });
  
    //call update function every 80 nanoseconds
    setInterval(function() {
      update(c, ctx);
    }, 80);
  }
  
  
  function update(c, ctx) {
    if (backgroundImage) {
      ctx.drawImage(backgroundImage, 0, 0, 640, 480);
    }
    ctx.rect(20, 20, 150, 100);
    ctx.stroke();
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;video id="video" width="640" height="480" autoplay&gt;&lt;/video&gt;
  &lt;button id="snap"&gt;Snap Photo&lt;/button&gt;
  &lt;canvas id="canvas" width="640" height="480"&gt;&lt;/canvas&gt;</code></pre>
  </div>
  </div>
  </p>