Advertisement
STANAANDREY

greyscale web camera

Oct 28th, 2023 (edited)
855
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.99 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Black and White Camera Stream</title>
  7.     <style>
  8.         #video {
  9.             display: none;
  10.         }
  11.  
  12.         #canvas {
  13.             width: 100%;
  14.             max-width: 640px;
  15.             height: auto;
  16.         }
  17.     </style>
  18. </head>
  19. <body>
  20.     <video id="video" autoplay></video>
  21.     <canvas id="canvas"></canvas>
  22.  
  23.     <script>
  24.         const video = document.getElementById('video');
  25.         const canvas = document.getElementById('canvas');
  26.         const ctx = canvas.getContext('2d');
  27.  
  28.         navigator.mediaDevices.getUserMedia({ video: true })
  29.             .then(function (stream) {
  30.                 video.srcObject = stream;
  31.             })
  32.             .catch(function (error) {
  33.                 console.error('Error accessing the camera: ', error);
  34.             });
  35.  
  36.         video.addEventListener('play', function () {
  37.             const width = video.videoWidth;
  38.             const height = video.videoHeight;
  39.             canvas.width = width;
  40.             canvas.height = height;
  41.  
  42.             function processFrame() {
  43.                 ctx.drawImage(video, 0, 0, width, height);
  44.                 const imageData = ctx.getImageData(0, 0, width, height);
  45.                 const data = imageData.data;
  46.  
  47.                 for (let i = 0; i < data.length; i += 4) {
  48.                    // Calculate grayscale value (0.299*R + 0.587*G + 0.114*B)
  49.                    const grayscale = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
  50.                    data[i] = grayscale; // Red channel
  51.                    data[i + 1] = grayscale; // Green channel
  52.                    data[i + 2] = grayscale; // Blue channel
  53.                }
  54.  
  55.                ctx.putImageData(imageData, 0, 0);
  56.                requestAnimationFrame(processFrame);
  57.            }
  58.  
  59.            processFrame();
  60.        });
  61.    </script>
  62. </body>
  63. </html>
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement