To capture an image from a camera using HTML5, you can use the getUserMedia() method in combination with the <video> and <canvas> elements. Here's an example code snippet:
<!DOCTYPE html>
<html>
<head>
<title>Camera capture demo</title>
</head>
<body>
<div>
<button id="capture-btn">Capture Image</button>
<canvas id="canvas" width="640" height="480"></canvas>
</div>
<script>
// Get the canvas and button elements
const canvas = document.getElementById('canvas');
const captureBtn = document.getElementById('capture-btn');
// Get user media (i.e., camera)
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
// Display video stream in <video> element
const video = document.createElement('video');
video.srcObject = stream;
video.autoplay = true;
document.body.appendChild(video);
// When capture button is clicked, draw current video frame on canvas
captureBtn.addEventListener('click', () => {
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
});
})
.catch(error => console.error('Error accessing camera:', error));
</script>
</body>
</html>
In this code, the getUserMedia() method is used to request access to the user's camera, and the resulting video stream is displayed in a <video> element. When the "Capture Image" button is clicked, the current video frame is drawn onto a <canvas> element using the drawImage() method.
You can modify this code to suit your specific needs, such as adding filters or uploading the captured image to a server.