How to allow the access automatically to the webcam - javascript

I am trying to develop a web page that access to my webcam using the following JS code:
(function( $ ){
$.fn.html5_qrcode = function(qrcodeSuccess, qrcodeError, videoError) {
'use strict';
var height = this.height();
var width = this.width();
if (height == null) {
height = 250;
}
if (width == null) {
width = 300;
}
var vidTag = '<video id="html5_qrcode_video" width="' + width + 'px" height="' + height + 'px"></video>'
var canvasTag = '<canvas id="qr-canvas" width="' + (width - 2) + 'px" height="' + (height - 2) + 'px" style="display:none;"></canvas>'
this.append(vidTag);
this.append(canvasTag);
var video = $('#html5_qrcode_video').get(0);
var canvas;
var context;
var localMediaStream;
$('#qr-canvas').each(function(index, element) {
canvas = element;
context = element.getContext('2d');
});
var scan = function() {
if (localMediaStream) {
context.drawImage(video, 0, 0, 307,250);
try {
qrcode.decode();
} catch(e) {
qrcodeError(e);
}
setTimeout(scan, 500);
} else {
setTimeout(scan,500);
}
}//end snapshot function
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
var successCallback = function(stream) {
video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
localMediaStream = stream;
video.play();
setTimeout(scan,1000);
}
// Call the getUserMedia method with our callback functions
if (navigator.getUserMedia) {
navigator.getUserMedia({video: true}, successCallback, videoError);
} else {
console.log('Native web camera streaming (getUserMedia) not supported in this browser.');
// Display a friendly "sorry" message to the user
}
qrcode.callback = qrcodeSuccess;
}; // end of html5_qrcode
})( jQuery );
I run my application and it works, but before that the cam is opened, I've got the access permission window, so I wander if there is any solution that allow me to open the webcam without ask.

For obvious reasons you can not turn people webcams on and start recording without consent.
Locally you can open up for specific features without asking with some vendors like Chrome by setting up policies. I have added abit of links in the comments

Related

getUserMedia image capture resolution vs. html video element size

Is there a way to capture a higher resolution image than the actual width of my onscreen video element which is showing my webcam image that I intend to capture?
Currently, I have set the width in getUserMedia to 1280, but my element is constrained to 640px. I'd like to still be storing images of 1280px wide so that I'm getting higher quality images.
Code:
<div id="video-container">
<h3 id="webcam-title">Add Photos</h3>
<video id="video" autoplay playsinline></video>
<select id="videoSource"></select>
<div id="take-photo-button" onclick="takeSnapshot();">TAKE PHOTO <div class="overlay"></div></div>
<canvas id="myCanvas" style="display:none;"></canvas>
<div id="snapshot-container"></div>
<div id="approval-form-submit">SAVE ORDER</div>
</div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script>
$(function() {
var video = document.querySelector('video');
var videoSelect = document.querySelector('select#videoSource');
var initialized = false;
//Obtain media object from any browser
navigator.getUserMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
var video_height, snapshot_height;
//var video_width = 1280;
var video_width = 640;
var container_width = 800;
var snapshot_margin = 10;
var snapshot_width = (container_width - snapshot_margin*6)/3;
//var snapshot_width = 1280;
function fillSelectWithDevices(deviceInfos) {
var value = videoSelect.value;
$(videoSelect).empty();
for (let i = 0; i !== deviceInfos.length; ++i) {
var deviceInfo = deviceInfos[i];
if (deviceInfo.kind === 'videoinput') {
var option = document.createElement('option');
option.value = deviceInfo.deviceId;
option.text = deviceInfo.label || `camera ${videoSelect.length + 1}`;
videoSelect.appendChild(option);
if(!initialized && deviceInfo.label==='Back Camera'){
value = deviceInfo.deviceId;
initialized = true;
}
}
if (Array.prototype.slice.call(videoSelect.childNodes).some(n => n.value === value)) {
videoSelect.value = value;
}
}
}
function gotStream(stream) {
window.stream = stream; // make stream available to console
video.srcObject = stream;
video.addEventListener('canplay', function(ev){
video_height = video.videoHeight * (video_width/video.videoWidth);
snapshot_height = video.videoHeight * (snapshot_width/video.videoWidth);
initCanvas();
// 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(video_height)) {
video_height = video_width * (3/4);
console.log("Can't read video height. Assuming 4:3 aspect ratio");
}
//video_width=640;
//video_height=480;
video.setAttribute('width', video_width);
video.setAttribute('height', video_height);
canvas.setAttribute('width', video_width);
canvas.setAttribute('height', video_height);
}, false);
return navigator.mediaDevices.enumerateDevices();
}
function handleError(error) {
console.log('navigator.getUserMedia error: ', error);
}
function start() {
if (window.stream) {
window.stream.getTracks().forEach(track => {
track.stop();
});
}
var videoSource = videoSelect.value;
var constraints = {
video: {deviceId: videoSource ? {exact: videoSource} : undefined,
facingMode: "environment",
width:1280},
audio: false
};
navigator.mediaDevices.getUserMedia(constraints).then(gotStream).then(fillSelectWithDevices).catch(handleError);
}
videoSelect.onchange = start;
start();
var canvas, ctx, container;
function initCanvas() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext('2d');
container = document.getElementById("snapshot-container");
//Reconstitute snapshots from form URI after failed submit
var image_list_field = $('#image-list-field'),
URI_array = image_list_field.val().split(','),
dataURI;
for(var i = 0;i<URI_array.length;i++){
if(URI_array[i]){
dataURI = "data:image/png;base64,"+URI_array[i];
displaySnapshot(dataURI);
}
}
}
// Capture a photo by fetching the current contents of the video
// and drawing it into a canvas, then converting that to a PNG
// format data URL. By drawing it on an offscreen canvas and then
// drawing that to the screen, we can change its size and/or apply
// other changes before drawing it.
takeSnapshot = function() {
alert (video_width + " " + video_height);
ctx.drawImage(video, 0, 0, video_width, video_height);
var data = canvas.toDataURL('image/png');
displaySnapshot(data);
}
function displaySnapshot(data){
var photo = document.createElement('img'),
snapshot_div = document.createElement('div'),
delete_text = document.createElement('p');
photo.setAttribute('src', data);
$(photo).css({"width":snapshot_width+"px"});
$(photo).addClass("snapshot-img");
$(snapshot_div).css({"width":snapshot_width+"px","height":snapshot_height+25+"px"});
$(delete_text).text("Delete Photo");
$(snapshot_div).append(photo).append(delete_text);
$(delete_text).on('click',function(){$(this).closest('div').remove()})
container.append(snapshot_div);
}
$('#approval-form-submit').on('click',function(e){
var form = $('#approval-form'),
image_list_field = $('#image-list-field'),
imageURI;
image_list_field.val("");
$('.snapshot-img').each(function(i, d){
imageURI = d.src.split(',')[1]+',';
image_list_field.val(image_list_field.val()+imageURI);
});
form.submit();
})

Store captured images using webcam and jQuery and HTML?

I'm doing one project using html and java-script but i'm new to java-script but i know little bit about js functionality..my project is based on Webcam and Captured images from my webcam i have completed upto Webcam and i takes pictures from my webcam and Now im problem is i want to save my captured images using captured button Id i tried but i cant get exact result.if any one knows please help me..
Here is my coding:'cam-video.html'
<div class="container" id="videophoto">
<div class="row">
<div class="col-sm-6 col-md-6">
<div id="container">
<video id="videoel" width="400" height="300" preload="auto" loop playsinline autoplay>
</video>
<canvas id="overlay" width="400" height="300"></canvas>
</div>
<button id="capture" class="pic">Capture</button><br />
<!--<img src="examples/media/audrey.jpg" />-->
<div class="alert alert-success" id="success-alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<img src="" id="photo" alt="photo">
Here is my javascript:'mine.js'
<script>
var vid = document.getElementById('videoel');
var vid_width = vid.width;
var vid_height = vid.height;
var overlay = document.getElementById('overlay');
var overlayCC = overlay.getContext('2d');
/*********** Setup of video/webcam and checking for webGL support *********/
function enablestart() {
var starttbutton = document.getElementById('starttbutton');
starttbutton.value = "start";
starttbutton.disabled = null;
}
var insertAltVideo = function(video) {
// insert alternate video if getUserMedia not available
if (supports_video()) {
if (supports_webm_video()) {
video.src = "./media/cap12_edit.webm";
} else if (supports_h264_baseline_video()) {
video.src = "./media/cap12_edit.mp4";
} else {
return false;
}
return true;
} else return false;
}
function adjustVideoProportions() {
// resize overlay and video if proportions of video are not 4:3
// keep same height, just change width
var proportion = vid.videoWidth/vid.videoHeight;
vid_width = Math.round(vid_height * proportion);
vid.width = vid_width;
overlay.width = vid_width;
}
function gumSuccess( stream ) {
// add camera stream if getUserMedia succeeded
if ("srcObject" in vid) {
vid.srcObject = stream;
} else {
vid.src = (window.URL && window.URL.createObjectURL(stream));
}
vid.onloadedmetadata = function() {
adjustVideoProportions();
vid.play();
}
vid.onresize = function() {
adjustVideoProportions();
if (trackingStarted) {
ctrack.stop();
ctrack.reset();
ctrack.start(vid);
}
}
}
function gumFail() {
// fall back to video if getUserMedia failed
insertAltVideo(vid);
document.getElementById('gum').className = "hide";
document.getElementById('nogum').className = "nohide";
alert("There was some problem trying to fetch video from your webcam, using a fallback video instead.");
}
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.msURL || window.mozURL;
// set up video
if (navigator.mediaDevices) {
navigator.mediaDevices.getUserMedia({video : true}).then(gumSuccess).catch(gumFail);
} else if (navigator.getUserMedia) {
navigator.getUserMedia({video : true}, gumSuccess, gumFail);
} else {
insertAltVideo(vid);
document.getElementById('gum').className = "hide";
document.getElementById('nogum').className = "nohide";
alert("Your browser does not seem to support getUserMedia, using a fallback video instead.");
}
vid.addEventListener('canplay', enablestart, false);
/*********** Code for face tracking *********/
var ctrack = new clm.tracker();
ctrack.init();
var trackingStarted = false;
function startVideo() {
// start video
vid.play();
// start tracking
ctrack.start(vid);
// var time=setTimeout("alert('Two Faces Not Allowed')",3500);
trackingStarted = true;
// start loop to draw face
drawLoop();
}
function drawLoop() {
requestAnimFrame(drawLoop);
overlayCC.clearRect(0, 0, vid_width, vid_height);
//psrElement.innerHTML = "score :" + ctrack.getScore().toFixed(4);
if (ctrack.getCurrentPosition()) {
ctrack.draw(overlay);
document.getElementById('photo').setAttribute('src', data);
}
}
/*********** Code for stats **********/
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
document.getElementById('container').appendChild( stats.domElement );
// update stats on every iteration
document.addEventListener('clmtrackrIteration', function(event) {
stats.update();
}, false);
</script>
<script type="text/javascript">
(function() {
var streaming = false,
video = document.querySelector('#video'),
canvas = document.querySelector('#canvas'),
buttoncontent = document.querySelector('#buttoncontent'),
photo = document.querySelector('#photo'),
startbutton = document.querySelector('#startbutton'),
width = 320,
height = 0;
navigator.getMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
navigator.getMedia({
video: true,
audio: false
},
function(stream) {
if (navigator.mozGetUserMedia) {
video.mozSrcObject = stream;
} else {
var vendorURL = window.URL || window.webkitURL;
video.src = vendorURL.createObjectURL(stream);
}
video.play();
},
function(err) {
console.log("An error occured! " + err);
}
);
video.addEventListener('canplay', function(ev) {
if (!streaming) {
height = video.videoHeight / (video.videoWidth / width);
video.setAttribute('width', width);
video.setAttribute('height', height);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
streaming = true;
}
}, false);
function takepicture(data_uri) {
video.style.display = "none";
canvas.style.display = "block";
startbutton.innerText= "RETAKE";
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(videoel, 0, 0, width, height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
var data = canvas.toDataURL('image/webp');
document.getElementById('photo').setAttribute('src', data);
document.getElementById("two").value = data;
document.myForm.sub();
document.getElementById('capture').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="' + data_uri + '"/>';
document.myForm.sub();
}
startbutton.addEventListener('click', function(ev) {
if(startbutton.innerText==="CAPTURE")
{
takepicture();
}
else
{
video.style.display = "block";
canvas.style.display = "none";
startbutton.innerText= "CAPTURE";
}
ev.preventDefault();
}, false);
})();
</script>
<script>
$(document).ready(function(){
$("#startbutton").click(function(){
$("#choosephoto").hide(1000);
});
});
</script>
Here is the code that i have tried how to save my captured images from webcam..
function takepicture(data_uri) {
video.style.display = "none";
canvas.style.display = "block";
startbutton.innerText= "RETAKE";
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(videoel, 0, 0, width, height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
var data = canvas.toDataURL('image/webp');
document.getElementById('photo').setAttribute('src', data);
document.getElementById("two").value = data;
document.myForm.sub();
document.getElementById('capture').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="' + data_uri + '"/>';
document.myForm.sub();
}
//$
the above part of code is i have tried.Can anyone help Me please.

capture photo from my site and save it on server

i want in my site to have a button and when the user click it, it will open the camera of the computer and take a picture and save it on my server.
code from html
<button type="button" id="button1">You want to see something COOL? (Not working from phone)</button><br />
<button id='reverse'>Reverse direction</button>
<video id='v'></video>
<style>
video {
position:absolute;
border-radius: 50%;
transform: rotateY(180deg);
-webkit-transform:rotateY(180deg);
-moz-transform:rotateY(180deg);
-o-transform:rotateY(180deg);
-ms-transform:rotateY(180deg);
}
</style>
javascript file
if (document.getElementById("button1").onclick == 'click' ){ //that is the problem,i want when the user click on the button to run the following code
var deltax = 10;
var deltay = 10;
var v;
var reverse;
var w; //will try to get dimensions of window
var h;
var x; //starting position
var y;
var vw = 300; //default dimensions of video
var vh = 210;
console.log("hello");
window.addEventListener('DOMContentLoaded', function() {
reverse = document.getElementById('reverse');
// When the reverse button is clicked, toggle the direction using deltax,deltay
reverse.addEventListener('click', changedeltas, false);
v = document.getElementById('v');
w = window.innerWidth;
h = window.innerHeight;
x = w/5;
y = h/5;
v.style.left = String(x)+"px";
v.style.top = String(y)+"px";
navigator.getUserMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
//alert("test "+navigator.getUserMedia);
var isStreaming = false;
// Cross browser
if (navigator.getUserMedia) {
// Request access to video and audio
navigator.getUserMedia(
{
video:true,
audio: false
},
function(stream) {
// Cross browser checks
var url = window.URL || window.webkitURL;
v.src = url ? url.createObjectURL(stream) : stream;
// Set the video to play
v.play();
},
function(error) {
alert('Something went wrong. (error code ' + error.code + ')');
return;
}
);
}
else {
alert('Sorry, the browser you are using doesn\'t support getUserMedia');
return;
}
// Wait until the video stream can play
v.addEventListener('canplay', function(e) {
if (!isStreaming) { //only do once
// videoWidth isn't always set correctly in all browsers
if (v.videoWidth > 0) {
vw = v.videoWidth;
vh = v.videoHeight;
}
ratio = vh/vw;
vw = Math.min(vw,w/5);
vh = vw*ratio;
v.setAttribute('width',vw);
v.setAttribute('height',vh);
//alert("now vw is "+vw+" vh is "+vh+" w is "+w+" h is "+h);
isStreaming = true;
}
}, false);
// Wait for the video to start to play
v.addEventListener('playing', function() {
tid = setInterval(moveit,50);
},false);
},false);
function moveit(){
x += deltax;
y += deltay;
//5 is fudge factor for hitting bottom and right wall to stop scrolling
if (((x+vw+5)>w) || (x<0)) {deltax = -deltax;}
if (((y+vh+5)>h) || (y<0)) {deltay = -deltay;}
v.style.top = String(y)+"px";
v.style.left = String(x)+"px";
}
function changedeltas(){
deltax = -deltax;
deltay = -deltay;
}
}
can anyone help me?
thanks

HTML 5 live video streaming from multiple sources

I have created a live video feed on a webpage with HTML 5, it works find but i am wondering is it possible to get video from many different sources.
How it works is it uses the built in webcam, grabs the video feed from that and adds it to the HTML of the page.
Is there any way I can duplicate this but grab video sources from another webcam? (i.e Have multiple live video feeds on the one page)
index.html
<!Doctype html>
<head>
<title>LiveStream</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="booth">
<video id="video" width="400" height="300" autoplay controls></video>
<canvas id="canvas" width="400" width="300">
<script src="video.js"></script>
</div>
</body>
video.js
(function(){
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
video = document.getElementById('video'),
vendorUrl = window.URL || window.webkitURL;
navigator.getMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
navigator.getMedia({
video: true,
audio: true
}, function(stream){
video.src = vendorUrl.createObjectURL(stream);
video.play();
}, function(error){
//Error occured!
});
})();
I have tried the following with MediaDevices.enumerateDevices but it isn't working!
(function(){
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
video = document.getElementById('video'),
vendorUrl = window.URL || window.webkitURL;
navigator.getMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia ||
navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
devices.forEach(function(device) {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
video = document.getElementById('video'),
vendorUrl = window.URL || window.webkitURL;
});
})
navigator.getMedia({
video: true,
audio: true
}, function(stream){
video.src = vendorUrl.createObjectURL(stream);
video.play();
}, function(error){
//Error occured!
});
}
)();
Important Note
The code below has not been tested in real conditions
I only have one webcam attached to my computer and it may fail on some systems !
You just have to make a second call to the getUserMedia, and in the prompt choose an other device.
There may have been some way in some implementations to choose the device, using video constraints, but I think it's not in the still in draft specs anymore.
Here is a way, using a button, which will create a new video element with a new stream each time :
(function() {
// We declare once what our video elements should look like
var video = document.createElement('video');
video.width = 400;
video.height = 300;
video.autoplay = true;
video.controls = true;
// Where will those be appended in doc
var container = document.querySelector('.booth'),
butt = document.querySelector('button'),
vendorUrl = window.URL || window.webkitURL;
navigator.getMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
function requestCam() {
navigator.getMedia({
video: true,
audio: true
}, function(stream) {
// clone our model video
var videoEl = video.cloneNode(true);
container.appendChild(videoEl);
// wait for the stream has been loaded in the video (kind of useless with autoplay = true)
videoEl.onloadedmetadata = function() {
this.play();
};
videoEl.src = vendorUrl.createObjectURL(stream);
}, function(error) {
console.log(error);
});
}
// attach the function to the button
butt.addEventListener('click', requestCam, false);
})();
button {
position: absolute;
}
<div class="booth">
<button>Add a new stream</button>
</div>
Fiddle for chrome which blocks stack-snippetĀ® getUserMedia() requests
To avoid the use of a button, you could chain your call to requestCam, but you'll have to call it after the last one was either approved or denied.
One way would be to insert it in the callback of the getUserMedia() ; but you may need to add some counter to avoid an infinite chain of calls.
(function() {
var video = document.createElement('video');
video.width = 400;
video.height = 300;
video.autoplay = true;
video.controls = true;
var container = document.querySelector('.booth'),
vendorUrl = window.URL || window.webkitURL;
navigator.getMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
var maxVideos = 3;
function requestCam(count) {
// we made it ? stop right now.
if(count >= maxVideos) return;
navigator.getMedia({
video: true,
audio: true
}, function(stream) {
var videoEl = video.cloneNode(true);
container.appendChild(videoEl);
videoEl.onloadedmetadata = function() {this.play();};
videoEl.src = vendorUrl.createObjectURL(stream);
// increment our counter
requestCam(++count);
}, function(error) {
console.log(error);
});
}
// make our first call with count=0
requestCam(0);
})();
<div class="booth">
</div>
Fiddle for chrome

Webcam Capture to <img>

Using javascript or Jquery I want to get the current image from the webcam feed on my page and put it in an tag.
I have a bit of script which generates tags dynamically with unique Id's so after generating one all I want to do is capture an image from the webcam at that exact moment and save the image in the generated tag. After taking the image I just want the webcam to carry until the next time it takes a picture.
I already have a webcam feed running using a library which does face tracking, however I want to extend this with this feature to create a gallery of captured images on the page.
The library I am using is ClmTracker
Creator of the library suggested calling getImageData(x,y,w,h) on the video element and I have tried this. also tried to implement tutorials I have seen on other websites but to no avail. It would seem the answer would need to be specific to my code. I have tried to use canvas instead of tags to put the image in to, but I kept getting errors due to them being created dynamically in the code.
var vid = document.getElementById('videoel');
var overlay = document.getElementById('overlay');
var overlayCC = overlay.getContext('2d');
/********** check and set up video/webcam **********/
function enablestart() {
var startbutton = document.getElementById('startbutton');
startbutton.value = "start";
startbutton.disabled = null;
}
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.msURL || window.mozURL;
// check for camerasupport
if (navigator.getUserMedia) {
// set up stream
var videoSelector = {
video: true
};
if (window.navigator.appVersion.match(/Chrome\/(.*?) /)) {
var chromeVersion = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
if (chromeVersion < 20) {
videoSelector = "video";
}
};
navigator.getUserMedia(videoSelector, function (stream) {
if (vid.mozCaptureStream) {
vid.mozSrcObject = stream;
} else {
vid.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
}
vid.play();
}, function () {
//insertAltVideo(vid);
alert("There was some problem trying to fetch video from your webcam. If you have a webcam, please make sure to accept when the browser asks for access to your webcam.");
});
} else {
//insertAltVideo(vid);
alert("This demo depends on getUserMedia, which your browser does not seem to support. :(");
}
vid.addEventListener('canplay', enablestart, false);
How can I capture an image from the webcam and put it in a div using the code above as a basis?
I'm not sure I can give any more details as I have not got the knowledge on how to do this.
First, draw it to a canvas:
var canvas = document.createElement('canvas');
canvas.height = video.height;
canvas.width = video.width;
canvas.getContext('2d').drawImage(video, 0, 0);
And now you can create the image:
var img = document.createElement('img');
img.src = canvas.toDataURL();
I cannot get to seem to get the screenshot porting working, but the webcam part is working fine, I'll update when complete.
JSFiddle
HTML
<div id="container">
<video autoplay="true" id="videoElement">dsasd</video>
<br>
<button onclick="snap()">Screenshot</button>
<canvas></canvas>
</div>
JS
var video = document.querySelector("#videoElement");
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({
video: true
}, handleVideo, videoError);
}
function handleVideo(stream) {
video.src = window.URL.createObjectURL(stream);
}
function videoError(e) {
// do something
}
// Get handles on the video and canvas elements
var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
// Get a handle on the 2d context of the canvas element
var context = canvas.getContext('2d');
// Define some vars required later
var w, h, ratio;
// Add a listener to wait for the 'loadedmetadata' state so the video's dimensions can be read
video.addEventListener('loadedmetadata', function() {
// Calculate the ratio of the video's width to height
ratio = video.videoWidth / video.videoHeight;
// Define the required width as 100 pixels smaller than the actual video's width
w = video.videoWidth - 100;
// Calculate the height based on the video's width and the ratio
h = parseInt(w / ratio, 10);
// Set the canvas width and height to the values just calculated
canvas.width = w;
canvas.height = h;
}, false);
// Takes a snapshot of the video
function snap() {
// Define the size of the rectangle that will be filled (basically the entire element)
context.fillRect(0, 0, w, h);
// Grab the image from the video
context.drawImage(video, 0, 0, w, h);
}
CSS
container {
margin: 0px auto;
width: 500px;
height: 375px;
border: 10px #333 solid;
}
videoElement, canvas {
width: 500px;
height: 375px;
background-color: #666;
}

Categories