Core JavaScript

Capture and Display a Camera

The JavaScript code example demonstrates how to capture a camera and display the content in a video element.

CameraCapture.html

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net's Javascript</title>
    <script type="text/javascript" src="CameraCapture.js"></script>
  </head>
  <body onload="Initialize()">
  </body>
</html>

CameraCapture.js

function CreateAndInsertVideoElement(iWidth, iHeight) {
	let qVideoElement = document.createElement ("video");
	qVideoElement.height			= iHeight;
	qVideoElement.width				= iWidth;
	qVideoElement.autoplay		= true;
	qVideoElement.playsInline	= true;
	qVideoElement.muted				= true;
	qVideoElement.loop				= true;
	return qVideoElement;
}
async function GetCamera(iWidth, iHeight) {
	let qVideoElement  = CreateAndInsertVideoElement(iWidth, iHeight);

	navigator.mediaDevices.getUserMedia({video:{width:iWidth, height:iHeight}})
		.then((mediaStream) => {  qVideoElement.srcObject = mediaStream; })
		.catch(qException => { console.error(`${qException.name}: ${qException.message}`); });

	qVideoElement.play();
	return qVideoElement;
}

function Initialize() {
	GetCamera(320, 180).then(qVideoElement => { document.body.appendChild(qVideoElement); });
}
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.