How to Build a Browser Document Scanner with OpenCV.js and JavaScript

A receipt photographed on a cluttered desk is not yet a scanned document. Before an app can save a flat, readable page, it has to find the four corners of the paper, discard everything around them, and warp the skewed quad into a rectangle. In a browser, that means either building the detection pipeline yourself or calling a detector designed for real-world capture conditions.

OpenCV.js can do it entirely client-side: convert the frame to grayscale, blur it, apply an Otsu threshold, find the largest contour, take its corner points, and run cv.warpPerspective. That path is free, needs no server, and is the clearest way to understand what document normalization actually does. It runs on a static image or canvas in this tutorial. It also assumes the page is the dominant high-contrast shape in the frame — an assumption that breaks on busy backgrounds, in low light, and when a corner falls out of view. For production scanning, Dynamsoft Capture Vision exposes a Document Detection & Normalization (DDN) module through CaptureVisionRouter, and the multi-page scanner tutorial builds auto-capture, quad editing, and PDF export on top of it.

The full pipeline implemented below:

Image / canvas → grayscale → Gaussian blur → Otsu threshold → contours
→ four corner points → cv.warpPerspective → flat, cropped page

Demo video:

What you’ll build: A DocumentScanner class that finds a page in a static image, returns its four corner points, and warps it into a flat, cropped canvas. Live camera capture and multi-page export belong to the production path linked below.

Choosing Between OpenCV.js and a Production Document Detector

  OpenCV.js contour pipeline (this tutorial) Dynamsoft Capture Vision DDN
Best for Learning the pipeline, prototypes, white page on dark background Production capture, cluttered backgrounds, low light, multi-page workflows
Boundary detection Grayscale, blur, Otsu threshold, largest contour, corner heuristic DetectDocumentBoundaries_Default through CaptureVisionRouter.capture()
Perspective correction cv.getPerspectiveTransform and cv.warpPerspective NormalizeDocument_Default through the same router
Live auto-capture, quad editing, PDF export Not implemented by this baseline Built into the multi-page scanner demo
Dependency Free, about 11 MB of OpenCV.js WASM dynamsoft-capture-vision-bundle@3.6.5000 via CDN plus a license key

The steps below implement the left column on static images. If you need the right column, start with How to Build a JavaScript Multi-Page Document Scanner Web App with Auto-Capture and PDF Export and try the online demo. Both paths produce the same flat page; they differ in how often detection succeeds.

Key Takeaways

  • OpenCV.js can detect document boundaries in the browser using grayscale conversion, Gaussian blur, thresholding, and contour detection — no server required.
  • Perspective transformation with cv.warpPerspective corrects skewed document photos into flat, cropped images directly in JavaScript.
  • This tutorial stops at static images: it returns four corner points and a corrected canvas. A live camera loop, stability-based auto-capture, quad editing, and multi-page export are separate work.
  • The basic OpenCV.js algorithm works well for high-contrast scenes (white document on dark background) but struggles with complex backgrounds — Dynamsoft Capture Vision’s DDN module handles those cases.
  • For a production scanner, the multi-page document scanner tutorial drives detection and normalization through CaptureVisionRouter and adds auto-capture, page ordering, and PDF export.

Common Developer Questions

How do I build a document scanner in the browser using OpenCV.js?

Build a detection pipeline that reads the source image into OpenCV.js, converts it to grayscale, blurs it, thresholds it, finds contours, and then picks the largest document-like boundary. This article wraps that workflow in a DocumentScanner class and runs it from a small browser UI.

How do I correct perspective distortion on a scanned document image with JavaScript?

Once you have the four document corners, compute the target rectangle and use cv.warpPerspective to map the skewed quadrilateral into a flat page image. That is the core step that turns a photographed document into a usable scan.

How do I add live camera document detection and auto-capture to a web app?

You can draw each getUserMedia() frame onto a hidden canvas and call detect() on it, but this baseline has no stability check — it will fire while the page or the camera is still moving. For unattended auto-capture, the multi-page scanner tutorial runs detection frame by frame through CaptureVisionRouter and gates the shutter on an IoU plus area-delta stabilizer; the online demo shows that behavior. This tutorial deliberately stops at static images.

When should I move from OpenCV.js to a production document detector?

Move when detection has to survive cluttered backgrounds, low light, partial occlusion, or unattended auto-capture. The contour pipeline below assumes one dominant high-contrast quad; Dynamsoft Capture Vision’s DDN module returns a detected quad frame by frame through CaptureVisionRouter.capture(). The multi-page scanner tutorial shows that path end to end, and the online demo lets you test it with your own camera.

Prerequisites

To follow this tutorial you need:

  • Node.js (v16 or later) and npm installed
  • A modern browser with WebAssembly support (Chrome, Firefox, Edge, Safari)
  • No license key is needed for the steps below; for the production path, get a 30-day free trial license

Step 1: Create a New Vite Project

Create a new project with Vite and the typescript template:

npm create vite@latest OpenCVDocumentScanner -- --template vanilla-ts

Step 2: Include OpenCV.js in Your Project

In index.html which is used for development, include OpenCV.

<script type="text/javascript">
  var Module = {
    // https://emscripten.org/docs/api_reference/module.html#Module.onRuntimeInitialized
    onRuntimeInitialized() {
      document.getElementById('status').innerHTML = 'OpenCV.js is ready.';
    }
  };
</script>
<script async src="https://docs.opencv.org/4.13.0/opencv.js" type="text/javascript"></script>

Pin a specific version so the tutorial stays reproducible. https://docs.opencv.org/4.x/opencv.js tracks the latest documentation build (currently 4.13.0) and can change underneath you. Because the script loads with async, wait until window.cv.Mat exists before constructing DocumentScanner; the 4.13.0 build was verified against the sample used in this tutorial.

Step 3: Build the Document Scanner Class

Next, create a document-scanner.ts file for the DocumentScanner class.

export class DocumentScanner {
  private cv:any;
  constructor() {
    if (!("cv" in window)) {
      throw new Error("OpenCV not found");
    }else{
      this.cv = window["cv"];
    }
  }
}

In the constructor, add a property called cv to use the cv namespace to perform related functions.

Detect Document Boundaries Using Contours

Next, add a detect method to return the four corner points of a document.

export interface Point {
  x: number;
  y: number;
}

export class DocumentScanner {
  detect(source:HTMLImageElement|HTMLCanvasElement):Point[]{}
}

Then, let’s implement the method in steps.

  1. Read the image as mat from an image element or a canvas element.

    let cv = this.cv;
    const img = cv.imread(source);
    
  2. Convert the image to grayscale.

    const gray = new cv.Mat();
    cv.cvtColor(img, gray, cv.COLOR_RGBA2GRAY);
    
  3. Perform Gaussian blur to remove noise.

    const blur = new cv.Mat();
    cv.GaussianBlur(gray,blur,new cv.Size(5, 5),0,0,cv.BORDER_DEFAULT);
    
  4. Perform threshold to get a binary image.

    const thresh = new cv.Mat();
    cv.threshold(blur,thresh,0,255,cv.THRESH_BINARY + cv.THRESH_OTSU);
    
  5. Find the contours and get the biggest one as the document candidate.

    let contours = new cv.MatVector();
    let hierarchy = new cv.Mat();
    cv.findContours(thresh,contours,hierarchy,cv.RETR_CCOMP,
      cv.CHAIN_APPROX_SIMPLE);
    
    let maxArea = 0;
    let maxContourIndex = -1;
    for (let i = 0; i < contours.size(); ++i) {
      let contourArea = cv.contourArea(contours.get(i));
      if (contourArea > maxArea) {
        maxArea = contourArea;
        maxContourIndex = i;
      }
    }
    
    const maxContour = contours.get(maxContourIndex);
    
  6. Get the corner points by calculating the distance of points to the center point. Store them in an array according to the clockwise direction.

    const points = this.getCornerPoints(maxContour);
    

    The functions needed:

    distance(p1:Point, p2:Point) {
      return Math.hypot(p1.x - p2.x, p1.y - p2.y);
    }
    
    getCornerPoints(contour:any):Point[] {
      let cv = this.cv;
      let points:Point[] = [];
      let rect = cv.minAreaRect(contour);
      const center = rect.center;
    
      let topLeftPoint;
      let topLeftDistance = 0;
    
      let topRightPoint;
      let topRightDistance = 0;
    
      let bottomLeftPoint;
      let bottomLeftDistance = 0;
    
      let bottomRightPoint;
      let bottomRightDistance = 0;
    
      for (let i = 0; i < contour.data32S.length; i += 2) {
        const point = { x: contour.data32S[i], y: contour.data32S[i + 1] };
        const distance = this.distance(point, center);
        if (point.x < center.x && point.y < center.y) {
          if (distance > topLeftDistance) {
            topLeftPoint = point;
            topLeftDistance = distance;
          }
        } else if (point.x > center.x && point.y < center.y) {
          if (distance > topRightDistance) {
            topRightPoint = point;
            topRightDistance = distance;
          }
        } else if (point.x < center.x && point.y > center.y) {
          if (distance > bottomLeftDistance) {
            bottomLeftPoint = point;
            bottomLeftDistance = distance;
          }
        } else if (point.x > center.x && point.y > center.y) {
          if (distance > bottomRightDistance) {
            bottomRightPoint = point;
            bottomRightDistance = distance;
          }
        }
      }
      points.push(topLeftPoint as Point);
      points.push(topRightPoint as Point);
      points.push(bottomRightPoint as Point);
      points.push(bottomLeftPoint as Point);
      return points;
    }
    
  7. Release the memory and return the points.

    img.delete();
    gray.delete();
    blur.delete();
    thresh.delete();
    contours.delete();
    hierarchy.delete();
    return points;
    

Crop and Deskew the Document with Perspective Transformation

Next, add a crop method to run perspective transformation to get a deskewed and cropped image.

crop(source:HTMLImageElement|HTMLCanvasElement,points?:Point[],width?:number,height?:number):HTMLCanvasElement{}

Let’s talk about the details in steps.

  1. Run detect to get the points if it is not provided in the argument.

    if (!points) {
      points = this.detect(source);
    }
    
  2. Determine the width and height of the output image.

    If the width and height are not specified by the user, then use the longest vertical edge for the height and the longest horizontal edge for the width.

    if (!width) {
      width = Math.max(this.distance(points[0],points[1]),this.distance(points[2],points[3]));
    }
    if (!height) {
      height = Math.max(this.distance(points[0],points[3]),this.distance(points[1],points[2]));
    }
    
  3. Create a transformation matrix.

    let srcTri = cv.matFromArray(4, 1, cv.CV_32FC2, [
      points[0].x,
      points[0].y,
      points[1].x,
      points[1].y,
      points[3].x,
      points[3].y,
      points[2].x,
      points[2].y,
    ]);
    
    let dstTri = cv.matFromArray(4, 1, cv.CV_32FC2, [
      0,
      0,
      width,
      0,
      0,
      height,
      width,
      height,
    ]);
    
    let M = cv.getPerspectiveTransform(srcTri, dstTri);
    
  4. Perform perspective transformation.

    let warpedDst = new cv.Mat();
    let dsize = new cv.Size(width, height);
    cv.warpPerspective(img,warpedDst,M,dsize,cv.INTER_LINEAR,
      cv.BORDER_CONSTANT,
      new cv.Scalar()
    );
    
  5. Draw the result into a canvas element.

    const canvas = document.createElement("canvas");
    cv.imshow(canvas, warpedDst);
    
  6. Release the memory and return the canvas.

    img.delete()
    warpedDst.delete()
    return canvas;
    

Run the Document Scanner on an Image

We can now use the document scanner to get the cropped document image.

const img = document.getElementById("photo");
const documentScanner = new DocumentScanner();
const points = documentScanner.detect(img);
const canvas = documentScanner.crop(img,points);
document.getElementById("output").src = canvas.toDataURL();

Example — the detected quad on the input (left) and the perspective-corrected page (right):

Input with the detected quad and the normalized output

Limitations

The contour pipeline here is deliberately minimal: it assumes the page is the dominant high-contrast shape in a static image. It returns four corner points, but no confidence score and no stability check, so it cannot gate an unattended capture. Those two gaps are why live auto-capture belongs to a production detector rather than to this baseline.

Dynamsoft Capture Vision’s DDN module returns a detected quad frame by frame through CaptureVisionRouter. The multi-page scanner tutorial implements DetectDocumentBoundaries_Default and NormalizeDocument_Default with an IoU plus area-delta stabilizer, and the online demo lets you test that behavior on your own documents.

Common Issues and Edge Cases

  • Detection fails on complex or cluttered backgrounds. The Otsu thresholding and largest-contour approach assumes the document is the dominant shape. On busy backgrounds, smaller objects may merge into larger contours. Workaround: pre-crop the image to reduce background clutter, or switch to Dynamsoft Capture Vision’s DDN module as shown in the multi-page scanner tutorial.
  • Corner points return undefined when the document is partially obscured. If one corner falls outside the frame or overlaps with the edge, the distance-to-center heuristic cannot classify it. Always check for undefined in the returned points array before passing them to crop.
  • OpenCV.js WASM file is large (~11 MB for 4.13.0) and blocks page load. Load it with the async attribute and gate your scanner initialization behind the onRuntimeInitialized callback to avoid UI freezes.

Difficult Cases, Measured

Both images below were run through this exact pipeline on OpenCV.js 4.13.0. Neither is a clean “white page on a dark desk” shot.

Cluttered background. Bright objects on the desk survive Otsu thresholding and merge with the page. The largest contour is no longer the document, so the quad expands past the paper and the corner points land on background shapes. The normalized output measures 969 × 890 px and contains a skewed page plus background rectangles, instead of the roughly 620 × 800 px document.

Cluttered background: the detected quad is pulled outward and the output contains background shapes

Low contrast. A pale sheet on a pale desk is still separated, but only barely. The four corners land close to the true edges (620 × 798 px), while the page and its text are visibly washed out; a small change in lighting pushes this case past the threshold.

Low contrast: corners are found but the normalized page loses contrast

Enabling the Canny edges option did not rescue either case in these runs: the cluttered image produced 970 × 893 px (still the wrong region) and the low-contrast image 645 × 783 px. These are limits of the threshold-plus-largest-contour baseline rather than tuning problems, which is why the production path uses a dedicated document detector with a stability signal.

Source Code

The DocumentScanner class implemented above is available in the sample repository, alongside the Vite project that runs it.

For the production path, see How to Build a JavaScript Multi-Page Document Scanner Web App with Auto-Capture and PDF Export and its online demo.