Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <title>Webcam</title>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <style>
- html *{
- font-size: 35px !important;
- margin: 2px;
- }
- </style>
- </head>
- <body>
- <div class="camera">
- <video id="video">Video stream not available.</video>
- <button id="startbutton" onclick="takepicture();">Take photo</button>
- </div>
- <canvas id="canvas"> </canvas>
- <div class="output">
- <img id="photo" />
- </div>
- </body>
- <script>
- const width = 720; // We will scale the photo width to this
- let height = 0; // This will be computed based on the input stream
- let streaming = false;
- let video = document.getElementById("video");
- let canvas = document.getElementById("canvas");
- let photo = document.getElementById("photo");
- let startbutton = document.getElementById("startbutton");
- function startup() {
- navigator.mediaDevices
- .getUserMedia({ video: true, audio: false })
- .then((stream) => {
- video.srcObject = stream;
- video.play();
- })
- video.addEventListener("canplay",(ev) => {
- if (!streaming) {
- height = video.videoHeight / (video.videoWidth / width);
- // Firefox currently has a bug where the height can't be read from
- // the video, so we will make assumptions if this happens.
- if (isNaN(height)) {
- height = width / (4 / 3);
- }
- video.setAttribute("width", width);
- video.setAttribute("height", height);
- canvas.setAttribute("width", width);
- canvas.setAttribute("height", height);
- streaming = true;
- }
- },
- false
- );
- }
- function takepicture() {
- const context = canvas.getContext("2d");
- if (width && height) {
- canvas.width = width;
- canvas.height = height;
- context.drawImage(video, 0, 0, width, height);
- const data = canvas.toDataURL("image/png");
- photo.setAttribute("src", data);
- }
- }
- startup();
- </script>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement