Designed for web browsers based on the WebKit code library, such as Google Chrome. This code makes use of the WebKit-specific “webkitGetUserMedia” function, as a generic implementation of “getUserMedia” that works in the same way in all browsers has not yet been decided on. It should also be noted that it might be a fairly trivial task to modify the code to work in other browsers.
<html>
<body>
<script type="text/javascript">
// main
function main()
{
var sizeInPixels = new Coords(160, 120);
var imageCapturer = new ImageCapturer(sizeInPixels);
imageCapturer.initialize();
}
// classes
function Coords(x, y)
{
this.x = x;
this.y = y;
}
function ImageCapturer(sizeInPixels)
{
this.sizeInPixels = sizeInPixels;
}
{
ImageCapturer.prototype.captureAndDisplayImage = function()
{
var imageCaptured = this.captureImage();
this.displayImage(imageCaptured);
}
ImageCapturer.prototype.captureImage = function()
{
return this.videoInput;
}
ImageCapturer.prototype.displayImage = function(imageToDraw)
{
this.graphics.drawImage
(
imageToDraw,
0, 0,
this.sizeInPixels.x, this.sizeInPixels.y
);
}
ImageCapturer.prototype.initialize = function()
{
var divImageCapturer = document.createElement("div");
var divInput = document.createElement("div");
var videoInput = document.createElement("video");
videoInput.width = this.sizeInPixels.x;
videoInput.height = this.sizeInPixels.y;
videoInput.autoplay = true;
divInput.appendChild(videoInput);
divImageCapturer.appendChild(divInput);
this.videoInput = videoInput;
var divControls = document.createElement("div");
var buttonCaptureImage = document.createElement("button");
buttonCaptureImage.onclick = this.captureAndDisplayImage.bind(this);
buttonCaptureImage.innerHTML = "Capture Image";
divControls.appendChild(buttonCaptureImage);
divImageCapturer.appendChild(divControls);
var divOutput = document.createElement("div");
var canvasOutput = document.createElement("canvas");
canvasOutput.width = this.sizeInPixels.x;
canvasOutput.height = this.sizeInPixels.y;
divOutput.appendChild(canvasOutput);
divImageCapturer.appendChild(divOutput);
this.graphics = canvasOutput.getContext("2d");
navigator.webkitGetUserMedia // for Google Chrome
(
{ video: true },
// success
function(stream)
{
var streamAsObjectURL = window.URL.createObjectURL(stream);
videoInput.src = streamAsObjectURL;
videoInput.play();
},
// error
function()
{
throw "An error has occurred.";
}
);
document.body.appendChild(divImageCapturer);
}
}
// run
main();
</script>
</body>
</html>