GithubHelp home page GithubHelp logo

schmich / instascan Goto Github PK

View Code? Open in Web Editor NEW
2.9K 97.0 866.0 2.06 MB

HTML5 QR code scanner using your webcam

Home Page: https://schmich.github.io/instascan/

License: MIT License

JavaScript 93.37% Shell 6.63%
html5 qr-code qrcode quick-response webcam video camera javascript zxing emscripten

instascan's Introduction

Instascan Instascan

Real-time webcam-driven HTML5 QR code scanner. Try the live demo.

Installing

Note: Chrome requires HTTPS when using the WebRTC API. Any pages using this library should be served over HTTPS.

NPM

npm install --save instascan

const Instascan = require('instascan');

Bower

Pending. Drop a note if you need Bower support.

Minified

Copy instascan.min.js from the releases page and load with:

<script type="text/javascript" src="instascan.min.js"></script>

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Instascan</title>
    <script type="text/javascript" src="instascan.min.js"></script>
  </head>
  <body>
    <video id="preview"></video>
    <script type="text/javascript">
      let scanner = new Instascan.Scanner({ video: document.getElementById('preview') });
      scanner.addListener('scan', function (content) {
        console.log(content);
      });
      Instascan.Camera.getCameras().then(function (cameras) {
        if (cameras.length > 0) {
          scanner.start(cameras[0]);
        } else {
          console.error('No cameras found.');
        }
      }).catch(function (e) {
        console.error(e);
      });
    </script>
  </body>
</html>

API

let scanner = new Instascan.Scanner(opts)

Create a new scanner with options:

let opts = {
  // Whether to scan continuously for QR codes. If false, use scanner.scan() to manually scan.
  // If true, the scanner emits the "scan" event when a QR code is scanned. Default true.
  continuous: true,
  
  // The HTML element to use for the camera's video preview. Must be a <video> element.
  // When the camera is active, this element will have the "active" CSS class, otherwise,
  // it will have the "inactive" class. By default, an invisible element will be created to
  // host the video.
  video: document.getElementById('preview'),
  
  // Whether to horizontally mirror the video preview. This is helpful when trying to
  // scan a QR code with a user-facing camera. Default true.
  mirror: true,
  
  // Whether to include the scanned image data as part of the scan result. See the "scan" event
  // for image format details. Default false.
  captureImage: false,
  
  // Only applies to continuous mode. Whether to actively scan when the tab is not active.
  // When false, this reduces CPU usage when the tab is not active. Default true.
  backgroundScan: true,
  
  // Only applies to continuous mode. The period, in milliseconds, before the same QR code
  // will be recognized in succession. Default 5000 (5 seconds).
  refractoryPeriod: 5000,
  
  // Only applies to continuous mode. The period, in rendered frames, between scans. A lower scan period
  // increases CPU usage but makes scan response faster. Default 1 (i.e. analyze every frame).
  scanPeriod: 1
};

scanner.start(camera)

  • Activate camera and start scanning using it as the source. Returns promise.
  • This must be called in order to use scanner.scan or receive scan events.
  • camera: Instance of Instascan.Camera from Instascan.Camera.getCameras.
  • .then(function () { ... }): called when camera is active and scanning has started.
  • .catch(function (err) { ... })
    • Called when an error occurs trying to initialize the camera for scanning.
    • err: An Instascan.MediaError in the case of a known getUserMedia failure (see error types).

scanner.stop()

  • Stop scanning and deactivate the camera. Returns promise.
  • .then(function () { ... }): called when camera and scanning have stopped.

let result = scanner.scan()

  • Scan video immediately for a QR code.
  • QR codes recognized with this method are not emitted via the scan event.
  • If no QR code is detected, result is null.
  • result.content: Scanned content decoded from the QR code.
  • result.image: Undefined if scanner.captureImage is false, otherwise, see the scan event for format.

scanner.addListener('scan', callback)

  • Emitted when a QR code is scanned using the camera in continuous mode (see scanner.continuous).
  • callback: function (content, image)
    • content: Scanned content decoded from the QR code.
    • image: null if scanner.captureImage is false, otherwise, a base64-encoded WebP-compressed data URI of the camera frame used to decode the QR code.

scanner.addListener('active', callback)

  • Emitted when the scanner becomes active as the result of scanner.start or the tab gaining focus.
  • If opts.video element was specified, it will have the active CSS class.
  • callback: function ()

scanner.addListener('inactive', callback)

  • Emitted when the scanner becomes inactive as the result of scanner.stop or the tab losing focus.
  • If opts.video element was specified, it will have the inactive CSS class.
  • callback: function ()

Instascan.Camera.getCameras()

  • Enumerate available video devices. Returns promise.
  • .then(function (cameras) { ... })
    • Called when cameras are available.
    • cameras: Array of Instascan.Camera instances available for use.
  • .catch(function (err) { ... })
    • Called when an error occurs while getting cameras.
    • err: An Instascan.MediaError in the case of a known getUserMedia failure (see error types).

camera.id

  • Unique camera ID provided by the browser.
  • These IDs are stable and can be persisted across instances of your application (e.g. in localStorage).

camera.name

  • Camera name, including manufacturer and model
  • e.g. "Microsoft LifeCam HD-3000".

Compatibility

Instascan works on non-iOS platforms in any browser that supports the WebRTC/getUserMedia API, which currently includes Chome, Firefox, Opera, and Edge. IE and Safari are not supported.

Instascan does not work on iOS since Apple does not yet support WebRTC in WebKit and forces other browser vendors (Chrome, Firefox, Opera) to use their implementation of WebKit. Apple is actively working on WebRTC support in WebKit.

Performance

Many factors affect how quickly and reliably Instascan can detect QR codes.

If you control creation of the QR code, consider the following:

  • A larger physical code is better. A 2" square code is better than a 1" square code.
  • Flat, smooth, matte surfaces are better than curved, rough, glossy surfaces.
  • Include a sufficient quiet zone, the white border surrounding QR code. The quiet zone should be at least four times the width of an individual element in your QR code.
  • A simpler code is better. You can use this QR code generator to see how your input affects complexity.
  • For the same length, numeric content is simpler than ASCII content, which is simpler than Unicode content.
  • Shorter content is simpler. If you're encoding a URL, consider using a shortener such as goo.gl or bit.ly.

When scanning, consider the following:

  • QR code orientation doesn't matter.
  • Higher resolution video is better, but is more CPU intensive.
  • Direct, orthogonal scanning is better than scanning at an angle.
  • Blurry video greatly reduces scanner performance.
  • Auto-focus can cause lags in detection as the camera adjusts focus. Consider disabling it or using a fixed-focus camera with the subject positioned at the focal point.
  • Exposure adjustment on cameras can cause lags in detection. Consider disabling it or having a fixed white backdrop.

Example Setup

  • Purpose: To scan QR code stickers on paper cards and plastic bags.
  • Camera: Microsoft LifeCam HD-3000, 720p, fixed focus, around $30 USD.
  • Small support to ensure camera is focused on subject.
  • White paper backdrop to mitigate exposure adjustment.

Setup

Credits

Powered by the Emscripten JavaScript build of the C++ port of the ZXing Java library.

License

Copyright © 2016 Chris Schmich
MIT License. See LICENSE for details.

instascan's People

Contributors

askarby avatar schmich avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

instascan's Issues

Fix first-time use null camera name

let scanner = new Instascan.Scanner();
scanner.addListener('scan', function (content, image) {
  console.log(content);
});
Instascan.Camera.getCameras().then(function (cameras) {
  if (cameras.length > 0) {
    scanner.start(cameras[0]);
  } else {
    console.error('No cameras found.');
  }
});

When running this for the first time on a domain that the user doesn't trust yet, the cameras from getCameras have null names because the user hasn't yet allowed access to the camera.

When scanner.start is called, the user is prompted. When the user accepts, the app has to call getCameras again to actually get the names.

This should be at least called out in the documentation if not fixed with a more straightforward API.

Add click-to-scan functionality

  • Instead of always-on scanning
  • Add to API, e.g. scanner.scan()
  • Allow disabling continuous scanning with opts.continuous.
  • Uses same scan event path, should respect captureImage
  • Should ignore refractoryPeriod
  • Use promise for result? Duplicates effort with scan event, but allows for better control

Fix getImageData memory issue

instascan.js:26271 Uncaught RangeError:
Failed to execute 'getImageData' on 'CanvasRenderingContext2D':
Out of memory at ImageData creationanalyze
@ instascan.js:26271_analyze
@ instascan.js:26156_scan
@ instascan.js:26207(anonymous function)
@ instascan.js:26198
>>>> var data = this.canvasContext.getImageData(0, 0, this.sensorWidth, this.sensorHeight).data;
for (var i = 0, j = 0; i < data.length; i += 4, j++) {
  ZXing.HEAPU8[this.imageBuffer + j] = data[i];
}

Add README

  • Add README
  • Deployment steps
    • Direct copyable, static
    • HTTPS for WebRTC
    • CORS for POST
    • Supports subfolder deployment (http://foo.com/scan/)
  • QR code guidelines (autofocus, resolution, size, complexity)
  • Brief rundown of features
  • Screenshot of website/scan
  • API documentation, usage

Add setting to transform content

  • Can be complex or simple
  • Rules based transformations
  • e.g. regex match, text output
  • e.g. match: .*, transform: http://foo.com?q=$0
  • $1, $2, ... capture groups
  • Will still be treated as URL if result is URL formatted

Add support for webhook callbacks with scan results

  • URL (template)
  • Method: GET, POST, PUT, PATCH, etc.
  • Additional headers: (key, value)
  • Template variables
    • %r: raw content
    • %s: scanned content
    • %i: base64-encoded image data
  • Payload
    • Template if specified, otherwise default
    • JSON, form-encoded, ...
    • Auto-determine Content-Type header
  • Checkbox: include image data

MVP:

  • POST
  • User-specified URL
  • JSON payload
  • Option to include base64-encoded image data

Camera name is blank on first launch/permissions

  • Open Chrome in incognito
  • Open site
  • Notice prompt for permissions
  • Open instascan settings
  • Notice blank camera name
  • Issue: we call getCameras before our first call to webkitGetUserMedia, so the cameras do not enumerate properly
  • Fix: have to figure out how to do first-time discovery of cameras (ordering)

Handle case when saved camera is no longer present

  • Connect camera
  • Launch instascan
  • Select connected camera (saved in localStorage)
  • Close instascan
  • Disconnect camera
  • Reopen instascan
  • Camera preview does not launch since camera is no longer available
  • Need to fallback to default existing camera

Getting below issue when published on azure

Uncaught SyntaxError: Unexpected end of input
app.js:11 Uncaught ReferenceError: Instascan is not defined
at Ue.mounted (app.js:11)
at we (vue.min.js:6)
at Ue.e._mount (vue.min.js:6)
at Ue.$mount (vue.min.js:8)
at Ue.$mount (vue.min.js:8)
at Ue.Re.e._init (vue.min.js:6)
at new Ue (vue.min.js:6)
at app.js:1

Show scan is in process

Is there a way yo have a mark on the canvas to show the user a frame has been captured and an analyse is in progress?

Or better show like in a native app some dots over the recognized points ?

Improve demo usability

  • Show live/not live status
  • Show error if one occurs when enumerating cameras (e.g. camera access denied) instead of just "No cameras found"
  • Add button to retry camera access (e.g. if user blocks then wants to allow camera access)

Black screen with Xiaomi Redmi 4 Pro

The back camera of my Xiaomi Redmi 4 Pro phone shows only a black image.
The front camera instead works fine.
It seems to be a bug with this library because other javascript scanners like quaggaJS work fine with both cameras.
This bug is in the demo page too.

Make backgroundScan default to true

By default, backgroundScan should be true to avoid potentially confusing behavior (see #43). By making the user explicitly set backgroundScan to false, they should understand why the preview video disappears and reappears.

AMD environment compatibility.

When using the library inside a AMD (requireJS) app I get an error probably related with the loading of lodash module. There are plans to package the library as AMD or UMD? There is a workaround for this issue?

Uncaught TypeError: _.forEach is not a function
at Object.init (instascan.js:7995)
at Stamp (instascan.js:26856)
at Function.create (instascan.js:27056)
at Scanner._createStateMachine (instascan.js:30311)
at new Scanner (instascan.js:30150)
at scanQR (play.js:866)
at HTMLFieldSetElement. (play.js:528)
at HTMLFieldSetElement.dispatch (jquery-2.1.4.min.js:3)
at HTMLFieldSetElement.r.handle (jquery-2.1.4.min.js:3)

Fix demo for mobile

  • Fast scan period makes preview laggy (too much for mobile)
  • mirror setting doesn't work well (might be phone-dependent)
  • Layout is optimized for desktop, looks bad on mobile, need mobile-optimized, too

Make webrtc-adapter a peer dependency

See #45.

  • webrtc-adapter should be a peer dependency, not a direct dependency, of this library
  • Update installation instructions
    • Browsers: need to include instascan.min.js as well as adapter.min.js
    • Provide a fully bundled version (webrtc-adapter included)?
    • npm/yarn: npm install --save instascan webrtc-adapter
    • ...

Add QR considerations to README

If you control QR generation:

  • Size
  • Complexity
  • Border
  • Matte vs. glossy

Scanning:

  • Higher resolution typically provides better results, but is more CPU intensive
  • Example setup
  • Orientation doesn't matter
  • Camera autofocus/fixed-focus
  • Exposure compensation
  • Blurriness is bad
  • Angled/skewed is bad

`<video>` seems to get `visibility:hidden;` after change tab and back.

Here are my HTML.

<div id="video_container" style="align-items:center;display:flex;height:100%;justify-content:center;margin-bottom:0px;margin-left:0px;margin-right:0px;margin-top:2.5px;overflow:hidden;">
  <video id="video" width="50%" autoplay loop muted preload></video>
</div>

I am using the example codes.

let scanner = new Instascan.Scanner({ video: document.getElementById('video') });
scanner.addListener('scan', function (content) {
  console.log(content);
});
Instascan.Camera.getCameras().then(function (cameras) {
  if (cameras.length > 0) {
    scanner.start(cameras[0]);
  } else {
    console.error('No cameras found.');
  }
}).catch(function (e) {
  console.error(e);
});

Here is animated .gif of the problem. After I change tab (twice) the <video> gone although the DOM is still the same.

http://i.imgur.com/Qr4yp3E.gif

The screen shot of the <video> when it is gone.

http://i.imgur.com/vz7GcKt.png

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.