DEV Community

ColonelParrot
ColonelParrot

Posted on

How to make a mobile document scanner with just Javascript

We now live in an age where you no longer need to buy a $400 printer to scan documents. Tools like Adobe Scan and CamScanner allow you to do it straight from your phone!

Web developers are constantly pushing the limits of what can be accomplished on the web. Now, you can create a mobile document scanner with Javascript!

Let's make one ourselves.


Introduction

We will be using jscanify to do this.

The goal is to convert this image:

To this:


Setting up the environment

We'll be doing this in a web environment. If you want to do this server side or with React, jscanify supports it too (you'll need to check the documentation though).

<html>
  <body>
    <script src="https://docs.opencv.org/4.7.0/opencv.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/ColonelParrot/jscanify@master/src/jscanify.min.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Getting the image and scanning

Now, let's load an image and scan it:

<html>
  <body>
    <script src="https://docs.opencv.org/4.7.0/opencv.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/ColonelParrot/jscanify@master/src/jscanify.min.js"></script>
    <img src="https://colonelparrot.github.io/jscanify/images/test/test.png" crossorigin="anonymous" id="image" />
    <script>
      cv.onRuntimeInitialized = function() {
        function scan() {
          const scanner = new jscanify()
          const scanned = scanner.extractPaper(image, 386, 500)
          document.body.appendChild(scanned)
        }
        image.onload = scan

        if (image.complete) {
          scan()
        }
      }
    </script>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode

We execute the code when OpenCV has loaded by waiting for the onRuntimeInitialized event. Once loaded, we initialize jscanify to create the scanner, and with one line, extract the paper with the extractPaper method. The parameters in the method are the width and height respectively.

So that's it! It's that easy :)

Top comments (0)