How to Preview a Webcam in the Browser
In this article
This guide shows you how to display a live webcam feed directly in a web page using the browser's built-in getUserMedia API. You'll end up with a working HTML page that shows your camera's video stream in real time. No special software or server is needed—just a modern browser and a webcam (built-in or USB).
What You'll Need
- A computer with a webcam (or an external USB camera).
- A modern browser: Chrome, Edge, Firefox, or Safari (all support
getUserMedia). - A text editor (like Notepad, VS Code, or any code editor) to create the HTML file.
- Basic familiarity with HTML and JavaScript—but even if you're new, just copy and paste the code.
Step-by-Step
-
Create an HTML file. Open your text editor and create a new file. Name it something like
webcam-preview.html. -
Set up the basic HTML structure. Add the following skeleton to your file:
The<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Webcam Preview</title> </head> <body> <video id="webcam" autoplay playsinline></video> <script> // JavaScript will go here </script> </body> </html><video>element is where the live stream will appear. Theautoplayattribute makes it start playing immediately, andplaysinlineis important for iOS Safari to show the video inline instead of fullscreen. -
Write the JavaScript to access the camera. Inside the
<script>tags, add the following code:
This code grabs the video element, then callsconst video = document.getElementById('webcam'); async function startCamera() { try { const stream = await navigator.mediaDevices.getUserMedia({ video: true }); video.srcObject = stream; } catch (error) { console.error('Error accessing camera:', error); alert('Unable to access the webcam. Please check permissions.'); } } startCamera();getUserMediawith a request for video (no audio). The returned stream is assigned to the video element'ssrcObjectproperty, which displays it. - Save and open the file. Save your HTML file, then double-click it to open in your default browser. You should see a prompt asking for permission to use your camera. Click “Allow.”
- View your webcam feed. Once you allow access, the video element will show a live feed from your webcam. That's it—you've successfully previewed your webcam in the browser.
-
Optional: Add a stop button. To stop the camera, you can add a button and a function to stop the tracks. For example:
This is useful for saving battery or when you're done.<button id="stop">Stop Camera</button> // In script: document.getElementById('stop').addEventListener('click', () => { const stream = video.srcObject; if (stream) { stream.getTracks().forEach(track => track.stop()); video.srcObject = null; } });
Common Mistakes
- Forgetting
autoplayorplaysinline. Withoutautoplay, the video may not start automatically. On mobile, withoutplaysinline, the video might open fullscreen. - Not using
srcObject. Some old tutorials usevideo.src = URL.createObjectURL(stream), which is deprecated. Always usesrcObject. - Calling
getUserMediabefore the DOM is ready. If your script is in the<head>, the video element may not exist yet. Put the script at the end of the body or useDOMContentLoaded. - Ignoring the promise rejection. If the user denies permission or no camera is available, the promise rejects. Always handle the error with a
catch.
Tips
- Test with a fake camera if you don't have one. Chrome DevTools has a “More settings” → “Sensors” panel where you can simulate a camera. This helps in development.
- Use
facingModeto select front/back camera on mobile. For example,{ video: { facingMode: 'user' } }for front camera,{ facingMode: 'environment' }for back camera. - Set video constraints for resolution. You can request a specific resolution like
{ video: { width: 1280, height: 720 } }to get a higher quality feed. - Always stop the stream when not needed. This frees up the camera for other applications and saves resources.
Troubleshooting
If the webcam doesn't appear, try these steps:
- Check if the page is served over HTTPS or localhost.
getUserMediarequires a secure context. If you open the file directly viafile://, it may work in some browsers (like Chrome) but not all. If it fails, run a local server (e.g., using Python'shttp.serveror VS Code Live Server extension). - Verify camera permissions. Ensure you clicked “Allow” on the browser prompt. If you accidentally blocked it, check browser settings: in Chrome, go to site settings and reset camera permission.
- Check if another app is using the camera. Close Zoom, Teams, or any other software that might be using the webcam.
- Look at the browser console. Press F12, go to the Console tab, and see if there are any error messages. They often tell you exactly what's wrong.
- Try a different browser. If one browser doesn't work, try another to isolate the issue.
Frequently Asked Questions
Can I preview the webcam without a server?
Yes, in most modern browsers, opening the HTML file directly from your hard drive (file://) works fine for getUserMedia. However, some browsers or certain configurations may require a secure context (HTTPS or localhost). If it doesn't work, run a local server.
How do I stop the camera stream?
Call stream.getTracks().forEach(track => track.stop()) on the stream you got from getUserMedia. Then set video.srcObject = null to clear the video element.
Can I select a specific camera if I have multiple?
Yes, you can enumerate devices using navigator.mediaDevices.enumerateDevices() and then set the deviceId in the constraints. For example: { video: { deviceId: { exact: selectedDeviceId } } }.
Does this work on mobile phones?
Yes, it works on iOS Safari and Android Chrome. Make sure to include playsinline attribute to prevent fullscreen video on iOS.
Can I take a snapshot from the video?
Yes, you can draw the current video frame onto a canvas using canvas.drawImage(video, 0, 0) and then export it as an image using canvas.toDataURL().
Why is the video not showing but no error?
This often happens when the video element has no dimensions (e.g., width/height not set). Add CSS like #webcam { width: 100%; max-width: 640px; } or set width and height attributes in HTML.