How to Access the Webcam in JavaScript
Access the webcam in JavaScript with getUserMedia: show a live video, choose a camera, capture a photo to canvas, handle permission errors and stop the stream.

Video calls, profile photos, document scanning, QR readers and augmented reality demos all start the same way: the page asks the browser for the camera, the user agrees and a live video stream appears. The API behind it, navigator.mediaDevices.getUserMedia(), is short to use and has a long list of details around it: secure contexts, permission prompts and their outcomes, choosing between front and back cameras, resolution constraints, mirroring the preview, taking a still frame and releasing the camera so the indicator light goes off. This guide shows how to access the webcam in JavaScript: the requirements, requesting video and showing it in a <video> element, constraints for resolution and facing mode, listing and switching devices, capturing a photo with a canvas, mirroring, error handling, cleanup, privacy, mobile specifics and testing. The API is documented on MDN and works in all current browsers.
Requirements
getUserMedia() is available only in secure contexts: https:// pages and http://localhost. In any other context, navigator.mediaDevices is undefined. The call should follow a user action, such as clicking "Start camera", because it triggers a permission prompt. Inside an <iframe>, the frame needs allow="camera". The operating system may also have its own camera permission for the browser, which users must grant separately.
Show the camera in a video element
Request video, and assign the resulting stream to the srcObject of a <video> element. Set autoplay, muted and playsinline so that the video starts without controls and, on iOS, inline instead of fullscreen.
<video id="preview" autoplay muted playsinline></video>
<button id="start">Start camera</button>const video = document.querySelector("#preview");
document.querySelector("#start").addEventListener("click", async () => {
const stream = await navigator.mediaDevices.getUserMedia({ video: true });
video.srcObject = stream;
await video.play();
console.log(video.videoWidth, video.videoHeight);
});1280 720The stream is a MediaStream, and video.srcObject plays it directly with no URL. The video's pixel dimensions are known after the loadedmetadata event, and the play() promise resolves once playback starts. muted is not needed for a camera-only stream but is harmless and avoids autoplay restrictions.
Choose resolution and camera
Constraints refine the request. Give an ideal size and the browser picks the closest camera mode. On phones, facingMode selects the front or back camera.
const stream = await navigator.mediaDevices.getUserMedia({
video: {
width: { ideal: 1280 },
height: { ideal: 720 },
frameRate: { ideal: 30 },
facingMode: "user",
},
audio: false,
});
const settings = stream.getVideoTracks()[0].getSettings();
console.log(settings.width, settings.height, settings.frameRate, settings.facingMode);1280 720 30 userThe value "user" is the front camera, which is right for selfies and calls, and "environment" is the rear camera, which is right for scanning. Use ideal for preferences, and exact only when you cannot work without a value, because an exact constraint that cannot be met fails the call with OverconstrainedError. getSettings() reports what you actually got, which can differ from what you asked.
List and switch devices
enumerateDevices() lists the cameras. The label of each device is empty until the user has granted permission at least once, so call it after the first successful getUserMedia(). To switch, stop the old stream and request a new one with the chosen deviceId.
async function listCameras() {
const devices = await navigator.mediaDevices.enumerateDevices();
return devices.filter((device) => device.kind === "videoinput");
}
async function useCamera(deviceId) {
stopStream();
currentStream = await navigator.mediaDevices.getUserMedia({
video: { deviceId: { exact: deviceId } },
});
video.srcObject = currentStream;
}
const cameras = await listCameras();
console.log(cameras.map((camera) => camera.label));[ 'FaceTime HD Camera', 'Logitech C920' ]Fill a <select> with the cameras and call useCamera() on change. Listen to navigator.mediaDevices.addEventListener("devicechange", ...) to refresh the list when a camera is plugged in or removed.
Capture a photo
To take a still, draw the current video frame onto a canvas and export it. Set the canvas size to the video's natural size so that you get the full resolution, not the displayed size.
function takePhoto(video) {
const canvas = document.createElement("canvas");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext("2d").drawImage(video, 0, 0, canvas.width, canvas.height);
return new Promise((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.9));
}
document.querySelector("#snap").addEventListener("click", async () => {
const blob = await takePhoto(video);
const url = URL.createObjectURL(blob);
document.querySelector("#photo").src = url;
console.log(blob.type, Math.round(blob.size / 1024), "KB");
});image/jpeg 98 KBtoBlob() gives a file you can upload or download, and the object URL shows it in an <img>. Revoke the URL when you are done. For a camera preview that the user sees mirrored, as in a mirror, the saved photo is normally not mirrored; if you flip the preview with CSS, do not flip the capture unless you want it that way.
Mirror the preview
A front camera preview feels natural when mirrored, as in a bathroom mirror, and unnatural when not. Apply a transform in CSS and leave the stream untouched.
video.mirror {
transform: scaleX(-1);
}
video {
width: 100%;
max-width: 640px;
background: #000;
border-radius: 8px;
}(the preview is flipped horizontally; the captured frames are not)When you draw to a canvas and want the picture to match what the user saw, flip the canvas context before drawing with ctx.translate(width, 0) and ctx.scale(-1, 1).
Stop the camera
The camera stays on, with its indicator light, until every track of the stream has stopped. Always release it when the user finishes, closes the dialog or leaves the page.
let currentStream = null;
function stopStream() {
currentStream?.getTracks().forEach((track) => track.stop());
currentStream = null;
video.srcObject = null;
}
window.addEventListener("pagehide", stopStream);(the camera light turns off)Setting srcObject to null clears the video element. A forgotten stream also keeps the battery draining on a phone and blocks other applications from the camera on some systems.
Handle errors
Distinguish the failures, and tell the user what to do for each.
async function startCamera() {
try {
currentStream = await navigator.mediaDevices.getUserMedia({ video: true });
video.srcObject = currentStream;
return true;
} catch (error) {
switch (error.name) {
case "NotAllowedError":
showMessage("Camera access was denied. Allow it in your browser settings.");
break;
case "NotFoundError":
showMessage("No camera was found on this device.");
break;
case "NotReadableError":
showMessage("The camera is in use by another application.");
break;
case "OverconstrainedError":
showMessage("This camera cannot provide the requested quality.");
break;
default:
showMessage("Could not start the camera.");
}
return false;
}
}No camera was found on this device.If the user dismisses the prompt without choosing, the promise may stay pending in some browsers, or reject with NotAllowedError in others, so give the interface a way out. Check navigator.permissions.query({ name: "camera" }) in browsers that support it to show a helpful state before asking.
Scan QR codes and process frames
For reading barcodes, the BarcodeDetector API in supporting browsers can take a video element directly, and libraries such as jsQR work on canvas pixel data in all browsers. Process frames with requestVideoFrameCallback(), which calls your function for each new video frame and avoids wasted work.
function onFrame(now, metadata) {
console.log(metadata.width, metadata.height, Math.round(metadata.mediaTime * 1000));
video.requestVideoFrameCallback(onFrame);
}
video.requestVideoFrameCallback(onFrame);1280 720 1033Downscale the frame before heavy analysis, and run expensive work in a worker so the page stays responsive.
Privacy and trust
A camera is among the most sensitive permissions. Explain the purpose before the browser prompt appears. Show clear on-screen evidence that the camera is active. Do not record or upload frames without the user's action and awareness, and say where they go. Keep processing on the device when possible. Respect denial and offer an alternative such as uploading a file. Never start the camera on page load. On shared screens, consider a visible "camera on" label near the preview.
Mobile notes
On phones, use facingMode rather than device IDs for the first request, because IDs and labels change. Orientation can change the video's aspect ratio, so do not hard-code dimensions; read videoWidth and videoHeight. iOS Safari requires playsinline and a user gesture, and stops the camera when the page goes to the background. Some devices expose several rear lenses, with the main one not always first; ask for the default through facingMode: "environment", and offer a switcher. For a quick photo with the native camera application instead of live video, <input type="file" accept="image/*" capture="environment"> opens the system camera on mobile and returns a file, with no permission code at all.
<input type="file" accept="image/*" capture="environment">(a phone opens its camera app and returns the photo as a file)Testing
Chromium has flags for development and tests: --use-fake-device-for-media-stream supplies a synthetic video stream and --use-fake-ui-for-media-stream accepts the permission prompt automatically, and Playwright can pass them, or grant the camera permission to a context. Test denial by using a context without permission. Check that the stream stops, that switching devices releases the previous stream and that the layout works at different aspect ratios.
const context = await browser.newContext({ permissions: ["camera"] });
const page = await context.newPage();
await page.goto("https://localhost:3000/camera");
await page.click("#start");
console.log(await page.evaluate(() => document.querySelector("video").videoWidth > 0));true

