Capturing Photos with JavaScript using accessing the camera

mdshamsfiroz
4 min readOct 17, 2024

--

In today’s growing world, the ability to interact with device hardware has become increasingly important. One of the most exciting capabilities is accessing the camera directly from a web browser. This feature opens up a lot of possibilities, from selfie-taking apps to document scanners, all running within a web page. In this blog post, we’ll explore how to use JavaScript to access the camera and capture photos.

Setting Up the HTML Structure

First, create a basic HTML structure with elements for displaying the video stream and capturing photos:

<video id="video" autoplay></video>
<button id="captureButton">Take Photo</button>
<canvas id="canvas" style="display:none;"></canvas>
<img id="photo" alt="Captured photo will appear here">

Accessing the Camera

To access the camera, use the navigator.mediaDevices.getUserMedia() method:

const video = document.getElementById('video');
async function startCamera() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ video: true });
video.srcObject = stream;
} catch (err) {
console.error("Error accessing the camera", err);
}
}
startCamera();

This code requests access to the user’s camera and displays the video stream in the <video> element

Capturing a Photo

To capture a photo from the video stream, you’ll use an <canvas> element to draw a frame from the video:

const canvas = document.getElementById('canvas');
const photo = document.getElementById('photo');
const captureButton = document.getElementById('captureButton');
captureButton.addEventListener('click', () => {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
const imageDataUrl = canvas.toDataURL('image/jpeg');
photo.src = imageDataUrl;
});

This code does the following:

  1. Sets up the canvas to match the video dimensions.
  2. Draws the current video frame onto the canvas.
  3. Converts the canvas content to a data URL.
  4. Sets the src of the <img> element to display the captured photo

Handling Different Cameras

If you want to allow users to switch between front and rear cameras on mobile devices, you can modify the getUserMedia() call:

const constraints = {
video: {
facingMode: 'environment' // Use 'user' for front camera
}
};
navigator.mediaDevices.getUserMedia(constraints)
.then(/* ... */)
.catch(/* ... */);

To switch between cameras, you can toggle the facingMode between 'user' and 'environment'

Complete Code:-

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Camera Access and Photo Capture</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 20px;
}
#video {
width: 100%;
max-width: 640px;
height: auto;
border: 1px solid #ddd;
}
#photo {
width: 100%;
max-width: 640px;
height: auto;
border: 1px solid #ddd;
margin-top: 20px;
}
#captureButton {
font-size: 18px;
padding: 10px 20px;
margin-top: 20px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Camera Access and Photo Capture</h1>
<video id="video" autoplay playsinline></video>
<br>
<button id="captureButton">Take Photo</button>
<canvas id="canvas" style="display:none;"></canvas>
<img id="photo" alt="Captured photo will appear here">

<script>
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const photo = document.getElementById('photo');
const captureButton = document.getElementById('captureButton');

async function startCamera() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: 'environment'
}
});
video.srcObject = stream;
} catch (err) {
console.error("Error accessing the camera", err);
alert("Error accessing the camera: " + err.message);
}
}

captureButton.addEventListener('click', () => {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
const imageDataUrl = canvas.toDataURL('image/jpeg');
photo.src = imageDataUrl;
});

// Start the camera when the page loads
window.addEventListener('load', startCamera);
</script>
</body>
</html>

This code includes:

  1. An HTML structure with a video element for the camera stream, a button to capture photos, a hidden canvas for processing the image, and an img element to display the captured photo.
  2. Basic CSS styling to make the interface more user-friendly.
  3. JavaScript to:
  • Access the camera using navigator.mediaDevices.getUserMedia().
  • Set up an event listener for the capture button.
  • Capture a frame from the video stream and convert it to an image when the button is clicked.
  • Display the captured image.
  1. Error handling to alert the user if there’s an issue accessing the camera.
  2. The camera is set to use the rear camera by default (facingMode: 'environment'). You can change this to 'user' for the front camera

Output UI:-

Git Hub Code Link:- https://github.com/mdshamsfiroz/Arth-4-Tasks/blob/main/FullStack/Task2.html

So, whether you’re a tech enthusiast, a professional, or just someone who wants to learn more, I invite you to follow me on this journey. Subscribe to my blog and follow me on social media to stay in the loop and never miss a post.

Together, let’s explore the exciting world of technology and all it offers. I can’t wait to connect with you!”

Connect me on Social Media: https://linktr.ee/mdshamsfiroz

Happy coding! Happy learning!

--

--

mdshamsfiroz
mdshamsfiroz

Written by mdshamsfiroz

Trying to learn tool by putting heart inside to make something

No responses yet