Access Webcam with HTML5

Access Computers webcam with HTML5 and show the Stream inside a Browser. The shown Webcam stream should be inside a tag of 640x480 size.
1 answer

Access Webcam with HTML5

Solution and detailed comments are below. (save it as an .html file):

<!DOCTYPE html>
<meta charset="utf-8">
<title>Display Webcam Stream</title>

#container {
margin: 0px auto;
width: 640px;
height: 480px;

#videoElement {
width: 640px;
height: 480px;
background-color: #ffffff;

<div id="container">

<!-- The <video> tag specifies video, such as a movie clip or other video streams. -->
<video autoplay="true" id="videoElement">


//get the video tag from above
var video = document.querySelector("#videoElement");

//The navigator object contains information about the browser.
//getUserMedia - prompts the user for permission to use a media device such as a camera or microphone.
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;

if (navigator.getUserMedia) {
//If the user provides permission, the handleVideo callback is invoked on the calling application with a LocalMediaStream object as its argument.
navigator.getUserMedia({video: true}, handleVideo, videoError);

function handleVideo(stream) {
//set the webcamStrem as source for the video tag
video.src = window.URL.createObjectURL(stream);

function videoError(e) {
alert("Error: "+e);