Core JavaScript

Display Camera Video

This JavaScript program shows how to display the video from the default camera of a computer. When the program runs, you will be prompted to allow the program to access the camera. It is necessary to allow this to be able to see the video displayed.

DisplayCameraVideo.html

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

DisplayCameraVideo.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() {
	let qVideoElement = GetCamera(320, 180)
		.then(qVideoElement => { document.body.appendChild(qVideoElement); });
}
 

Output

 
 

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