JS Get image directly from video stream as data URL

How can I go directly from capturing video to data url in javascript? I want to display the image for the user as a modified version, but save the full size image. So how would I do that?

var PhotoBooth = { onMediaStream: function(stream) { PhotoBooth.canvas = $('canvas')[0]; PhotoBooth.context = PhotoBooth.canvas.getContext('2d'); PhotoBooth.localVideo = $('video')[0]; PhotoBooth.localVideo.src = window.URL.createObjectURL(stream); }, noStream: function() { console.log('FAIL TO GET WEBCAM ACCESS'); } }; getUserMedia( {video: true}, PhotoBooth.onMediaStream, PhotoBooth.noStream ); 

This is how I am currently saving the image for upload:

 PhotoBooth.context.drawImage(PhotoBooth.localVideo, 0, 0, 200, 150); $('#preview').show(); 

Then I retrieve the saved image like this:

 var dataUrl = PhotoBooth.canvas.toDataURL(); 

I would like to keep the canvas the same size by default, but keep the actual data. Basically, I want the canvas to show the size version, but support the full version.

+5
source share
1 answer

Here canvas supports the original 640x480 snapshot (use https script for Chrome):

 var start = () => navigator.mediaDevices.getUserMedia({ video: true }) .then(stream => video.srcObject = stream) .catch(log); var canvas = document.createElement("canvas"); canvas.width = 640; canvas.height = 480; var snap = () => { canvas.getContext('2d').drawImage(video, 0, 0, 640, 480); preview.getContext('2d').drawImage(canvas, 0, 0, 160, 120); } var log = msg => div.innerHTML += "<br>" + msg; 
 <button onclick="start()">Start!</button> <button onclick="snap()">Snap!</button><div id="div"></div> <video id="video" width="160" height="120" autoplay></video> <canvas id="preview" width="160" height="120"></canvas> 
+2
source

Source: https://habr.com/ru/post/1244544/


All Articles