This JavaScript program demonstrates how to capture an image from a video camera via the canvas and display it in an image element.
<!DOCTYPE html>
<html>
<head>
<title>XoaX.net's Javascript</title>
<style>
#idVideo {
float: left;
width: 480px;
height: 270px;
}
#idImage {
float: left;
width: 480px;
height: 270px;
background-color: gray;
}
#idButton {
clear: left;
display: block;
}
</style>
<script type="text/javascript" src="CameraImageCapture.js"></script>
</head>
<body onload="Initialize()">
<video id="idVideo">The video stream is not available.</video>
<img id="idImage" alt="The image captured from the video." />
<button id="idButton" onclick="CaptureImage()">Capture Image</button>
</body>
</html>
function Initialize() {
// Select the video element
let qVideoElement = document.getElementById('idVideo');
// Create the button element and add it to the body
navigator.mediaDevices.getUserMedia({video:{width:480, height:270}})
.then( function(qStream) {
qVideoElement.srcObject = qStream;
qVideoElement.play();
})
.catch( function(qException) {
console.error(`${qException.name}: ${qException.message}`);
});
}
function CaptureImage() {
// Create a canvas element to capture the image data on.
let qCanvasElement = document.createElement("canvas");
// Get its context
var qContext2D = qCanvasElement.getContext('2d');
qCanvasElement.width = 480;
qCanvasElement.height = 270;
// Select the video element
let qVideoElement = document.getElementById('idVideo');
qContext2D.drawImage(qVideoElement, 0, 0, 480, 270);
// Get the image as a dataURL
let qDataUrl = qCanvasElement.toDataURL('image/png');
// Get the image element
let qImageElement = document.getElementById('idImage');
qImageElement.setAttribute('src', qDataUrl);
}© 20072025 XoaX.net LLC. All rights reserved.