How to Capture High-Resolution Photos in the Browser with JavaScript getUserMedia

getUserMedia() can request a high-resolution camera stream, but the browser and camera negotiate the actual size. An ideal 3840×2160 request is a preference, not a guarantee: inspect the video track’s getSettings() and the playing video’s videoWidth and videoHeight before deciding what you captured.

Try this minimal example on HTTPS or localhost. Click Capture and allow camera access; the canvas receives one frame at the video’s intrinsic dimensions. Open the browser console to compare the requested and actual sizes. The camera is stopped after the frame is drawn.

<button id="capture">Capture</button>
<video id="preview" autoplay muted playsinline></video>
<canvas id="photo"></canvas>
<script>
  document.querySelector('#capture').onclick = async () => {
    let stream;
    try {
      stream = await navigator.mediaDevices.getUserMedia({
        video: { width: { ideal: 3840 }, height: { ideal: 2160 } },
        audio: false
      });
      const video = document.querySelector('#preview');
      video.srcObject = stream;
      await video.play();
      const track = stream.getVideoTracks()[0];
      console.log('Track settings:', track.getSettings());
      console.log('Video dimensions:', video.videoWidth, video.videoHeight);
      const canvas = document.querySelector('#photo');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      canvas.getContext('2d').drawImage(video, 0, 0);
    } catch (error) {
      console.error('Camera capture failed:', error);
    } finally {
      if (stream) stream.getTracks().forEach(track => track.stop());
    }
  };
</script>

A canvas sized to the video captures a stream frame; making the canvas larger only scales that frame. ImageCapture.takePhoto() requests a still image from the camera and may produce different dimensions, depending on the device and browser. An HTML file input with accept="image/*" capture may open the device’s native camera app; its output and behavior also depend on the platform. The full demo below explores all three approaches and lets you select a camera.

Measured Resolution Across Two Browsers

On November 9, 2026, we ran three ideal requests from localhost on Windows 11 Enterprise (build 26200), in headless Chrome 156 and headless Edge 157.0.4341.42, against a USB Global Shutter Camera (32e4:0234). Camera permission was granted automatically. Each request selected that camera with deviceId: { exact: ... }, recorded getSettings(), the video’s intrinsic dimensions and the dimensions decoded from the takePhoto() blob, then stopped the track before the next request. Both browsers returned identical values.

Requested stream Negotiated track / video takePhoto() blob
640×480 640×480 640×480
1920×1080 1920×1080 1920×1080
3840×2160 1920×1200 1920×1200

A 4K preference negotiated a 1920×1200 stream on this camera, and the still image matched the stream in these runs. Neither result establishes a maximum or predicts other cameras; it only shows that an ideal request is not a guarantee.

The system also lists a virtual camera device, but it is excluded from these results. With no image or video source loaded, that device has no frame to deliver: its takePhoto() calls failed with UnknownError and its reported size reflected the virtual driver’s default rather than constraint negotiation. Treat such a device as measurable only after a source is loaded, and do not read its failures as a limitation of ImageCapture.

These runs are Windows plus Chromium in headless mode, with one physical camera and automatically granted permission. They do not cover Firefox, Safari, mobile browsers, an interactive permission prompt or a second physical camera. Treat the table as an example of how negotiation behaves, not a compatibility matrix; test your own browser and device before relying on a particular size.

What you’ll build: A browser-based app that requests high-resolution frames and compares canvas capture, Image Capture, and HTML Media Capture.

Key Takeaways

  • Use getUserMedia width and height constraints to request a stream size; inspect the track and video dimensions to see what the browser actually provides.
  • The Image Capture API can produce a still at a different resolution from the live preview when supported; check the resulting image dimensions.
  • For the simplest high-resolution capture without live preview, use <input type="file" accept="image/*" capture> to invoke the device’s native camera app.
  • High-resolution browser capture is essential for document scanning, barcode reading, and OCR workflows where image detail directly affects accuracy.

Common Developer Questions

How do I capture a high-resolution photo from a webcam in JavaScript?

Open the camera with navigator.mediaDevices.getUserMedia(), attach the stream to a video element, and request a specific width and height such as 3840x2160 through the video constraints before the stream starts. Once the preview is live, either draw the current frame onto a canvas with drawImage() or, when supported, call ImageCapture.takePhoto() to save a still image from the active video track, whose dimensions may differ from the preview.

What is the maximum camera resolution I can get with getUserMedia in the browser?

getUserMedia does not guarantee a fixed maximum because the final size depends on the physical camera and the browser’s constraint negotiation. The demo lets you request 3840×2160, but in the measured runs a 4K request produced a 1920×1200 stream on the test camera. After the stream starts, check video.videoWidth and video.videoHeight to see what was actually granted, because an ideal request may be satisfied with different dimensions. Required constraints such as exact can instead reject with OverconstrainedError.

How do I use the Image Capture API to take a 4K photo in Chrome?

In Chrome, get the first video track from localStream, create new ImageCapture(track), and call await imageCapture.takePhoto() inside the photo button handler. The returned Blob can be previewed with URL.createObjectURL(blob), and if ImageCapture is unavailable or throws, the sample falls back to captureFrame() to capture a video frame through the canvas path.

Prerequisites

  • A modern browser (Chrome, Edge, Firefox, or Safari) with camera access.
  • A device with a camera that supports the desired resolution (e.g., 1080p or 4K).
  • HTTPS or localhost — getUserMedia requires a secure context.
  • If you want to extend this demo with document boundary detection or barcode scanning, get a 30-day free trial license for Dynamsoft Capture Vision.

Step 1: Create the HTML Boilerplate

Create a new HTML file with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Take a High Resolution Photo</title>
  <style>
  .home {
    display: flex;
    align-items: center;
    flex-direction: column;
  }
  </style>
</head>
<body>
  <div class="home">
    <h2>Take a Photo</h2>
  </div>
  <script>
  </script>
</body>
</html>

Step 2: Capture a Photo with getUserMedia

  1. Request camera permission when the page is loaded.

    window.onload = async function() {
      await requestCameraPermission();
    }
    async function requestCameraPermission() {
      const constraints = {video: true, audio: false};
      const stream = await navigator.mediaDevices.getUserMedia(constraints);
      const tracks = stream.getTracks();
      for (let i=0;i<tracks.length;i++) {
        const track = tracks[i];
        track.stop();  // stop the opened camera
      }
    }
    
  2. List camera devices in a select element.

    HTML:

    <label>
      Camera:
      <select id="cameraSelect"></select>
    </label>
    

    JavaScript:

    const cameraSelect = document.getElementById("cameraSelect");
    window.onload = async function() {
      await loadCameraDevices();
      loadCameraDevicesToSelect();
    }
    async function loadCameraDevices(){
      const constraints = {video: true, audio: false};
      const stream = await navigator.mediaDevices.getUserMedia(constraints);
      const devices = await navigator.mediaDevices.enumerateDevices();
      for (let i=0;i<devices.length;i++){
        let device = devices[i];
        if (device.kind == 'videoinput'){ // filter out audio devices
          cameraDevices.push(device);
        }
      }
      const tracks = stream.getTracks(); // stop the camera to avoid the NotReadableError
      for (let i=0;i<tracks.length;i++) {
        const track = tracks[i];
        track.stop();
      }
    }
    
    function loadCameraDevicesToSelect(){
      for (let i=0;i<cameraDevices.length;i++){
        let device = cameraDevices[i];
        cameraSelect.appendChild(new Option(device.label,device.deviceId))
      }
    }
    
  3. Start the selected camera and display the camera preview in a video element.

    document.getElementById("startCameraBtn").addEventListener('click', (event) => {
      console.log("start camera");
      let options = {};
      if (cameraSelect.selectedIndex != -1) {
        options.deviceId = cameraSelect.selectedOptions[0].value;
      }
      play(options);
    });
    
    
    function play(options) {
      stop(); // close before play
      video.style.display = "block";
      let constraints = {};
      if (options.deviceId){
        constraints = {
          video: {deviceId: options.deviceId},
          audio: false
        }
      }else{
        constraints = {
          video: {width:1280, height:720,facingMode: { exact: "environment" }},
          audio: false
        }
      }
      navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
        localStream = stream;
        // Attach local stream to video element      
        video.srcObject = stream;
      }).catch(function(err) {
        console.error('getUserMediaError', err, err.stack);
      });
    }
    
    function stop() {
      try{
        if (localStream){
          const tracks = localStream.getTracks();
          for (let i=0;i<tracks.length;i++) {
            const track = tracks[i];
            track.stop();
          }
        }
      } catch (e){
        alert(e.message);
      }
    };
    
  4. Use a canvas element to capture a frame.

    Append a canvas element in the HTML and then use it to capture a camera frame and display it in an img element.

    HTML:

    <button id="takePhotoBtn">Take Photo</button>
    <video class="camera" muted autoplay="autoplay" playsinline="playsinline" webkit-playsinline></video>
    <br/>
    <canvas id="hiddenCanvas"></canvas>
    <img id="photoTaken" />
    

    JavaScript:

    document.getElementById("takePhotoBtn").addEventListener('click', async (event) => {
      let src;
      src = captureFrame();
      document.getElementById("photoTaken").src = src;
    });
       
    function captureFrame(){
      let w = video.videoWidth;
      let h = video.videoHeight;
      canvas.width  = w;
      canvas.height = h;
      let ctx = canvas.getContext('2d');
      ctx.drawImage(video, 0, 0, w, h);
      return canvas.toDataURL("image/jpeg")
    }
    
  5. Specify a high resolution so that the frame captured has a high quality.

    We can define several common resolutions in a select and try to use the selected resolution.

    HTML:

    <label>
      Desired Resolution:
      <select id="resolutionSelect">
        <option value="640x480">640x480</option>
        <option value="1280x720">1280x720</option>
        <option value="1920x1080">1920x1080</option>
        <option value="3840x2160">3840x2160</option>
      </select>
    </label>
    

    We need to specify the resolution in the constraints for getUserMadia.

    function play(options){
      if (options.deviceId){
        constraints = {
          video: {deviceId: options.deviceId},
          audio: false
        }
      }else{
        constraints = {
          video: {width:1280, height:720,facingMode: { exact: "environment" }},
          audio: false
        }
      }
      if (resolutionSelect.selectedIndex != -1) {
        let width = parseInt(resolutionSelect.selectedOptions[0].value.split("x")[0]);
        let height = parseInt(resolutionSelect.selectedOptions[0].value.split("x")[1]);
        constraints["video"]["width"] = width;
        constraints["video"]["height"] = height;
      }
      //...
    }
    
  6. Take a photo using the Image Capture API

    If the browser supports the Image Capture API, we can use it to take a photo instead of capturing a frame with canvas.

    document.getElementById("takePhotoBtn").addEventListener('click', async (event) => {
      let src;
      if ("ImageCapture" in window) {
        try {
          const track = localStream.getVideoTracks()[0];
          let imageCapture = new ImageCapture(track);
          let blob = await imageCapture.takePhoto();
          src = URL.createObjectURL(blob);
        }catch(e) {
          src = captureFrame();
        }
      }else{
        src = captureFrame();
      }
      document.getElementById("photoTaken").src = src;
    });
    
  7. Display the size of the image taken.

    document.getElementById("photoTaken").onload = function(){
      let img = document.getElementById("photoTaken");
      document.getElementById("info").innerText = "Image Width: " + img.naturalWidth +"\nImage Height: " + img.naturalHeight;
    }
    

Step 3: Take a Photo with HTML Media Capture

  1. Add an input element for selecting an image file.

    <button id="loadFileBtn">
      Load File
    </button>
    <input type="file" id="file" onchange="loadImageFromFile();" accept=".jpg,.jpeg,.png,.bmp" />
    

    The input element is hidden and triggered with a button.

    document.getElementById("loadFileBtn").addEventListener('click', async (event) => {
      document.getElementById("file").click();
    });
    
  2. When an image file is selected, load it into an img element.

    function loadImageFromFile(){
      let fileInput = document.getElementById("file");
      let files = fileInput.files;
      if (files.length == 0) {
        return;
      }
      let file = files[0];
      fileReader = new FileReader();
      fileReader.onload = function(e){
        document.getElementById("photoTaken").src = e.target.result;
      };
      fileReader.onerror = function () {
        console.warn('oops, something went wrong.');
      };
      fileReader.readAsDataURL(file);
    }
    

Choose the Right Approach for Your Use Case

If you need to do live image processing before taking a photo, you have to use the getUserMedia approach.

If you only need to take a high-resolution photo, you can use the input element.

Common Issues and Edge Cases

  • Camera resolution falls back silently. If you request 3840×2160 but the camera only supports 1920×1080, the browser silently picks the closest supported resolution. Always check video.videoWidth and video.videoHeight after the stream starts to confirm the actual resolution.
  • getUserMedia requires a secure context. The API only works over HTTPS or on localhost. If you test on a plain HTTP URL, navigator.mediaDevices will be undefined.
  • Image Capture API availability. ImageCapture.takePhoto() is only supported in Chromium-based browsers (Chrome, Edge, Opera). Firefox and Safari fall back to the canvas capture method.

Source Code

Get the complete sample project source code on GitHub

There is also a document scanner demo that captures high-resolution photos: Get the complete sample project source code on GitHub. It uses Dynamsoft Document Normalizer to detect document boundaries and correct the document image.