181 Views
To access a USB camera using HTML code, you typically need to use the getUserMedia API, which is part of the WebRTC (Real-Time Communication) standard. This API allows web browsers to access the user’s camera and microphone directly.
Here’s a basic example of HTML code to access a USB camera:
<html>
<head>
<title>yawot.com</title>
</head>
<body>
<video autoplay></video>
<script>
// get video dom element
const video = document.querySelector('video');
// request access to webcam
navigator.mediaDevices.getUserMedia({video: {width: 300, height:280}}).then((stream) => video.srcObject = stream);
// returns a frame encoded in base64
const getFrame = () => {
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
return data;
}
const WS_URL = location.origin.replace(/^http/, 'ws');
const FPS = 3;
const ws = new WebSocket(WS_URL);
ws.onopen = () => {
console.log(`Connected to ${WS_URL}`);
setInterval(() => {
ws.send(getFrame());
}, 5000 / FPS);
}
</script>
</body>
</html>
n this example:
- We have an HTML5 video element (
<video>
) with anid
of “videoElement”. - In the JavaScript part, we use the
navigator.mediaDevices.getUserMedia
method to request access to the user’s camera. We specify{ video: true }
in the options object to request access to the video stream. - If the user grants permission, the video stream is attached to the
<video>
element usingvideo.srcObject = stream;
. - If there’s an error (e.g., the user denies access or the device doesn’t support getUserMedia), an error message is logged to the console.
Make sure to run this code on a web server (even a local one) as getUserMedia won’t work if you just open the HTML file directly due to browser security restrictions.
387000cookie-checkusb camera access with html code