Advertisement
metalx1000

HTML5 Webcam

Nov 12th, 2022
2,098
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 2.19 KB | Source Code | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.   <head>
  4.     <title>Webcam</title>
  5.     <meta charset="utf-8">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1">
  7.     <style>
  8.       html *{
  9.         font-size: 35px !important;
  10.         margin: 2px;
  11.       }
  12.     </style>
  13.   </head>
  14.   <body>
  15.     <div class="camera">
  16.       <video id="video">Video stream not available.</video>
  17.       <button id="startbutton" onclick="takepicture();">Take photo</button>
  18.     </div>
  19.     <canvas id="canvas"> </canvas>
  20.     <div class="output">
  21.       <img id="photo" />
  22.     </div>
  23.   </body>
  24.   <script>
  25.     const width = 720; // We will scale the photo width to this
  26.     let height = 0; // This will be computed based on the input stream
  27.     let streaming = false;
  28.  
  29.     let video = document.getElementById("video");
  30.     let canvas = document.getElementById("canvas");
  31.     let photo = document.getElementById("photo");
  32.     let startbutton = document.getElementById("startbutton");
  33.  
  34.     function startup() {
  35.       navigator.mediaDevices
  36.       .getUserMedia({ video: true, audio: false })
  37.       .then((stream) => {
  38.         video.srcObject = stream;
  39.         video.play();
  40.       })
  41.  
  42.       video.addEventListener("canplay",(ev) => {
  43.         if (!streaming) {
  44.           height = video.videoHeight / (video.videoWidth / width);
  45.  
  46.           // Firefox currently has a bug where the height can't be read from
  47.           // the video, so we will make assumptions if this happens.
  48.  
  49.           if (isNaN(height)) {
  50.             height = width / (4 / 3);
  51.           }
  52.  
  53.           video.setAttribute("width", width);
  54.           video.setAttribute("height", height);
  55.           canvas.setAttribute("width", width);
  56.           canvas.setAttribute("height", height);
  57.           streaming = true;
  58.         }
  59.       },
  60.       false
  61.       );
  62.  
  63.     }
  64.  
  65.     function takepicture() {
  66.       const context = canvas.getContext("2d");
  67.       if (width && height) {
  68.        canvas.width = width;
  69.         canvas.height = height;
  70.         context.drawImage(video, 0, 0, width, height);
  71.  
  72.         const data = canvas.toDataURL("image/png");
  73.         photo.setAttribute("src", data);
  74.       }
  75.     }
  76.  
  77.     startup();
  78.   </script>
  79. </html>
  80.  
Tags: html5 webcam
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement