How to Run an HTML File on Localhost with Webcam Mirror (Live Checkbox Example)

Have you ever wanted to build a simple web app that accesses your webcam and lets you interact with the video feed in real time? Maybe a mirror tool with toggleable effects? In this guide, we’ll walk through creating a webcam mirror application with a live checkbox that toggles a mirror effect. But first, we’ll solve a critical hurdle: running the HTML file on localhost (a local web server) instead of directly from your filesystem.

Why localhost? Modern browsers restrict webcam access for security reasons when pages are opened via the file:// protocol (i.e., double-clicking the HTML file). By running the file on a local server (localhost), we ensure the browser recognizes the context as secure, allowing webcam access.

By the end of this tutorial, you’ll have:

  • A functional HTML file that accesses your webcam.
  • A live checkbox to toggle a mirror effect on the video feed.
  • A clear understanding of how to run local HTML files on localhost.

Table of Contents#

  1. Prerequisites
  2. Step 1: Set Up the HTML File
  3. Step 2: Write the Webcam Mirror Code
  4. Step 3: Run the File on Localhost
  5. Step 4: Test the Live Checkbox Feature
  6. Troubleshooting Common Issues
  7. Conclusion
  8. References

Prerequisites#

Before we start, ensure you have the following tools:

  • A Text Editor: We’ll use Visual Studio Code (VS Code) for this tutorial, but any editor (Sublime Text, Atom, etc.) works.
  • A Modern Web Browser: Chrome, Firefox, Edge, or Safari (all support webcam APIs).
  • Basic Knowledge: Familiarity with HTML, CSS, and JavaScript will help, but we’ll explain every step in detail.

Step 1: Set Up the HTML File#

First, let’s create a project folder and set up the basic HTML structure.

1.1 Create a Project Folder#

  • Create a new folder on your computer (e.g., webcam-mirror-app).
  • Open this folder in your text editor (in VS Code: File > Open Folder).

1.2 Create the HTML File#

Inside the folder, create a new file named index.html. This will be our main file.

Add the basic HTML boilerplate:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Webcam Mirror with Live Checkbox</title>
    <style>
        /* We'll add CSS styles here later */
    </style>
</head>
<body>
    <!-- Webcam and controls will go here -->
</body>
</html>

Step 2: Write the Webcam Mirror Code#

Now, let’s add the webcam feed and the live checkbox. We’ll break this into two parts: HTML elements (for the video and checkbox) and JavaScript (for webcam access and live updates).

2.1 Add HTML Elements#

First, add a video element to display the webcam feed and a checkbox to toggle the mirror effect. Update the <body> section of your index.html as follows:

<body>
    <h1>Webcam Mirror</h1>
    
    <!-- Video element to display webcam feed -->
    <video id="webcam" autoplay playsinline></video>
    
    <!-- Checkbox to toggle mirror effect -->
    <div class="controls">
        <label>
            <input type="checkbox" id="mirrorCheckbox"> 
            Toggle Mirror Effect
        </label>
    </div>
 
    <script>
        // JavaScript code will go here
    </script>
</body>
  • <video id="webcam" autoplay playsinline>: The autoplay attribute starts the video automatically, and playsinline ensures it works on mobile devices.
  • Checkbox: The <input type="checkbox"> with ID mirrorCheckbox will trigger the mirror effect when checked.

2.2 Style the Elements (CSS)#

Add CSS to style the video and checkbox. Update the <style> section in the <head>:

body {
    font-family: Arial, sans-serif;
    max-width: 800px;
    margin: 20px auto;
    padding: 0 20px;
}
 
#webcam {
    border: 3px solid #333;
    border-radius: 8px;
    width: 100%;
    max-width: 640px;
    height: auto;
    background: #000; /* Black background before webcam starts */
}
 
.controls {
    margin-top: 20px;
    font-size: 1.1em;
}

This centers the content, adds a border to the video, and styles the checkbox section.

2.3 Add JavaScript for Webcam Access & Live Toggle#

Now, let’s write the JavaScript to:

  1. Access the webcam.
  2. Toggle the mirror effect when the checkbox is checked.

Add this code inside the <script> tag in the <body>:

// Select elements from the DOM
const webcamElement = document.getElementById('webcam');
const mirrorCheckbox = document.getElementById('mirrorCheckbox');
 
// Toggle mirror effect when checkbox is clicked
mirrorCheckbox.addEventListener('change', () => {
    if (mirrorCheckbox.checked) {
        webcamElement.style.transform = 'scaleX(-1)'; // Flip horizontally
    } else {
        webcamElement.style.transform = 'scaleX(1)'; // Reset
    }
});
 
// Access the webcam and stream video to the <video> element
async function startWebcam() {
    try {
        // Request webcam access (video only)
        const stream = await navigator.mediaDevices.getUserMedia({ 
            video: true, // Enable video
            audio: false // Disable audio (we don't need it)
        });
 
        // Set the video source to the webcam stream
        webcamElement.srcObject = stream;
 
    } catch (error) {
        // Handle errors (e.g., user denies permission)
        console.error('Webcam access failed:', error);
        alert('Could not access your webcam. Please check permissions and try again.');
    }
}
 
// Start the webcam when the page loads
startWebcam();

How It Works:#

  • Webcam Access: navigator.mediaDevices.getUserMedia({ video: true }) requests permission to access the webcam. If granted, it returns a media stream, which we assign to the video element’s srcObject.
  • Mirror Toggle: The checkbox’s change event listener checks if the box is checked. If yes, it applies transform: scaleX(-1) to the video, flipping it horizontally (mirror effect). Unchecking resets it.

Step 3: Run the File on Localhost#

Now, we need to run the HTML file on a local server (localhost). Opening it directly via file:// will fail because browsers block webcam access for security. Here are 3 easy ways to set up a local server:

Method 1: VS Code Live Server (Easiest for Beginners)#

If you use VS Code:

  1. Install the Live Server extension (search for it in the Extensions tab).
  2. Right-click index.html in the VS Code file explorer.
  3. Select Open with Live Server.

VS Code will start a local server (usually at http://localhost:5500) and open the page in your browser.

Method 2: Python Built-In Server (No Installation Needed)#

If you have Python installed (check with python --version in terminal):

  1. Open a terminal/command prompt.
  2. Navigate to your project folder:
    cd path/to/your/webcam-mirror-app  # Replace with your folder path
  3. Start the server:
    • For Python 3.x:
      python -m http.server 8000
    • For Python 2.x:
      python -m SimpleHTTPServer 8000
  4. Open your browser and go to http://localhost:8000.

Method 3: Node.js http-server (For Node Users)#

If you have Node.js installed:

  1. Install the http-server package globally:
    npm install -g http-server
  2. Navigate to your project folder in terminal:
    cd path/to/your/webcam-mirror-app
  3. Start the server:
    http-server
  4. Open http://localhost:8080 in your browser.

Step 4: Test the Live Checkbox Feature#

Once the server is running and the page loads:

  1. Allow Webcam Access: Your browser will prompt for permission to access the webcam. Click "Allow".
  2. Test the Checkbox: Check the "Toggle Mirror Effect" box. The video feed should flip horizontally (mirror effect). Uncheck it to return to normal.

Troubleshooting Common Issues#

1. "Webcam Access Failed" Error#

  • Cause: You denied webcam permission, or no webcam is available.
  • Fix: Go to your browser’s settings, find "Site Settings", and allow webcam access for localhost.

2. Port Already in Use (e.g., "Address already in use")#

  • Cause: Another server is using the port (e.g., 8000, 5500).
  • Fix: Use a different port. For Python: python -m http.server 3000 (uses port 3000). For Live Server: Right-click the status bar and change the port.

3. Video Not Displaying#

  • Check: Ensure autoplay is set on the <video> element (required for automatic playback).
  • Browser Compatibility: Use Chrome, Firefox, or Edge. Older browsers (e.g., IE) don’t support getUserMedia.

Conclusion#

You’ve built a webcam mirror app with a live checkbox toggle! By running the file on localhost, you overcame browser security restrictions, and the JavaScript code enables real-time interaction with the webcam feed.

This project demonstrates core web skills:

  • Using browser APIs (e.g., getUserMedia for webcam access).
  • Live DOM manipulation (toggling CSS classes with JavaScript).
  • Setting up a local development server.

From here, you could expand the app by adding more effects (e.g., grayscale, sepia) or saving snapshots to a canvas.

References#