Advertisement
metalx1000

Basic HTML5 webcam photo taker

Mar 4th, 2016
729
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <html>
  2.  
  3. <head>
  4.   <script>
  5.     // Put event listeners into place
  6.     window.addEventListener("DOMContentLoaded", function() {
  7.       // Grab elements, create settings, etc.
  8.       var canvas = document.getElementById("canvas"),
  9.         lastPhoto = canvas.getContext("2d"),
  10.         video = document.getElementById("video"),
  11.         videoObj = { "video": true },
  12.         errBack = function(error) {
  13.           console.log("Video capture error: ", error.code);
  14.         };
  15.  
  16.       // Put video listeners into place
  17.       if(navigator.getUserMedia) { // Standard
  18.         navigator.getUserMedia(videoObj, function(stream) {
  19.           video.src = stream;
  20.           video.play();
  21.         }, errBack);
  22.       } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
  23.         navigator.webkitGetUserMedia(videoObj, function(stream){
  24.           video.src = window.webkitURL.createObjectURL(stream);
  25.           video.play();
  26.         }, errBack);
  27.       }
  28.       else if(navigator.mozGetUserMedia) { // Firefox-prefixed
  29.         navigator.mozGetUserMedia(videoObj, function(stream){
  30.           video.src = window.URL.createObjectURL(stream);
  31.           video.play();
  32.         }, errBack);
  33.       }
  34.       // Trigger photo take
  35.       document.getElementById("video").addEventListener("click", function() {
  36.         var context = newCan();
  37.         lastPhoto.drawImage(video, 0, 0, 640, 480);
  38.         context.drawImage(video, 0, 0, 640, 480);
  39.       });
  40.     }, false);
  41.  
  42.     function newCan(){
  43.       // Grab elements, create settings, etc.
  44.       var canvas = document.createElement("canvas"),
  45.         context = canvas.getContext("2d"),
  46.         video = document.getElementById("video"),
  47.         videoObj = { "video": true },
  48.         errBack = function(error) {
  49.           console.log("Video capture error: ", error.code);
  50.         };
  51.       canvas.width = 640;
  52.       canvas.height = 480;
  53.       var photos = document.getElementById("photos");
  54.       photos.appendChild(canvas);
  55.       return context;
  56.     }
  57.   </script>
  58. </head>
  59. <body>
  60.   <h1>Webcam App By Kris Occhipinti</h1>
  61.   <video id="video" width="640" height="480" autoplay></video>
  62.   <canvas id="canvas" width="640" height="480"></canvas>
  63.   <div id="photos"></div>
  64.   <hr>
  65.   <p>Tap Video to take a photo.  Right Click/Long Hold to "save image as"</p>
  66.   <p>Based on code by David Walsh https://davidwalsh.name/browser-camera</p>
  67. </body>
  68. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement