npm package 'instascan'

Popularity: Medium (more popular than 90% of all packages)
Description: Webcam-driven QR code scanner.
Installation: npm install instascan
Last version: 1.0.0 (Download)
Homepage: https://github.com/schmich/instascan
Size: 0 kB
License: MIT
Keywords: qr, code, quick, response, scan, scanner, webcam, realtime

Activity

Last modified: January 26, 2017 1:06 AM (6 years ago)
Versions released in one year: 0
Weekly downloads: 1,828
06/12/202205001,0001,5002,000released versions / week
  • Versions released
  • Weekly downloads

What's new in version 1.0.0

Delta between version 0.0.3 and version 1.0.0

Source: Github
Commits:
  • ba1520a62f7c1d5a05622f331053897cfaa29933, July 18, 2016 7:21 AM:
    Fix Exception/Error naming.
  • dae9f496b8bba3215377ab771251455eb70fe758, July 18, 2016 7:34 PM:
    Fix visibility check when transitioning into the active state. Remove camera setting. Updating the camera should be done using scanner.start.
  • cf3de588a7f8b99307cbb3456e84909ca683e6ca, July 18, 2016 8:53 PM:
    Mark more fields as private. Support changing options on Scanner.
  • 3e4a91ec7c9ce8126cd3bbc270a0dd2c9c7057eb, July 18, 2016 8:57 PM:
    Make Scanner.stop async.
  • e816929108630f17995ea0b7e91f6a7ed26933de, July 18, 2016 9:21 PM:
    Fix #25: Add browser support to README.
  • 63995744570e6385a5b92116a59ae8860f0c668d, July 18, 2016 9:30 PM:
    Add installation instructions to README.
  • 87bf7d7d6cdc8a24835f864da1336db7ab3d04ad, July 18, 2016 9:42 PM:
    Support changing of Scanner.mirror property.
  • cecfb7147026b12199e8a7a209ea0dbcdf65c390, July 18, 2016 9:45 PM:
    Refactor FSM creation into its own method.
  • 3628ae9d246fcc8d594c6fec9ec359648eafab79, July 18, 2016 10:31 PM:
    Add Scanner.continuous setting to control whether scanning should be done continuously. Add Scanner.scan to force an immediate scan.
  • a7cd972cf02a70f7ff05ce3d7aba83291d9da876, July 18, 2016 10:43 PM:
    Add continuous/click-to-scan updates to API.
  • 2394ad881eb1a6ecdfba2e70aa3ad11498970dfc, July 19, 2016 12:34 AM:
    Add additional API notes. Tweak style.
  • 7e6340ff23a7a40a342613b733c6e7a493b9cf76, July 19, 2016 12:37 AM:
    Elaborate on camera.id.
  • f83c09746f0e195091c09c5be7f240d1dbc9a1e3, July 19, 2016 2:01 AM:
    Fix #20: Add QR considerations to README.
  • 3f6eda345a5c88f730545975036f5a46253b1a33, July 19, 2016 2:12 AM:
    Add QR code to README.
  • 00d19ea7627b45eed703b57eb38bc165a85d8b56, July 19, 2016 2:26 AM:
    Add keyword to package.
  • 8e39d0bb49e38cc26df96180340bdf2822bc8ae8, July 19, 2016 4:36 AM:
    Add example setup to README.
  • bcf1ef26ae16821765ce1c7fc4e70db2a7e5169a, July 19, 2016 4:38 AM:
    Move compatibility section up.
  • 33ef9521549f568f79856d933a31dfc2c753d748, July 19, 2016 5:18 AM:
    Add HTTPS requirement note.
  • 58c7acc85e531961355ebd177ba4cbf12d1a26a3, July 19, 2016 5:20 AM:
    Fix capitalization.
  • e82dd96cc1af4e18cff286fd27df7b88015c1c5f, July 23, 2016 8:34 AM:
    Add API cross-references.
  • 4323cc40f621fa459012e6d9e361d2f26c9d15cc, July 23, 2016 8:42 AM:
    Add more cross-references. Clean up some opts documentation.
  • 203fc39958bcf8cd40a8c0fed03936ff87882482, July 23, 2016 8:50 AM:
    Add Bower note.
  • 620126fb6b4df25c20790544aa7e31521cff4c7e, August 3, 2016 4:47 AM:
    Fix #35: Set active/inactive class on video element based on camera state.
  • ce261d556e45a3ea92f21f41e2f19856e15c1e37, August 3, 2016 4:51 AM:
    Add README notes about active/inactive CSS class on the video element.
  • 7db37b01b5909faac696117cc609037a97b24fdc, August 3, 2016 7:31 AM:
    Use average of red, green, and blue components for grayscale QR image component.
  • b89672724700c3ec317cc5ce2e15878560788e35, January 26, 2017 12:59 AM:
    var -> let in README
  • 5a3492a0d93cc329bb9824b7ab0b0c0878486f0e, January 26, 2017 1:05 AM:
    Bump to 1.0.0.
Files changed:
README.md CHANGED
@@ -1,5 +1,29 @@
1
- # Instascan
2
- Webcam-driven HTML5 QR code scanner.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  ## Example
5
 
@@ -8,12 +32,12 @@ Webcam-driven HTML5 QR code scanner.
8
  <html>
9
  <head>
10
  <title>Instascan</title>
11
- <script type="text/javascript" src="dist/instascan.min.js"></script>
12
  </head>
13
  <body>
14
  <video id="preview"></video>
15
  <script type="text/javascript">
16
- var scanner = new Instascan.Scanner({ video: document.getElementById('preview') });
17
  scanner.addListener('scan', function (content, image) {
18
  console.log(content);
19
  });
@@ -30,56 +54,106 @@ Webcam-driven HTML5 QR code scanner.
30
 
31
  ## API
32
 
33
- ### `new Instascan.Scanner(opts)`
34
 
35
  - Create a new scanner with options.
36
- - `opts.video`: The HTML element to use for the camera's video preview. Must be a `<video>` element. By default, an invisible element will be created to host the video.
 
37
  - `opts.mirror`: Whether to horizontally mirror the video preview. This is helpful when trying to scan a QR code with a user-facing camera. Default `true`.
38
- - `opts.backgroundScan`: Whether to actively scan when the tab is not active. When `false`, this reduces CPU usage when the tab is not active. Default `false`.
39
- - `opts.refractoryPeriod`: The period, in milliseconds, before the same QR code will be recognized in succession. Default `5000`.
40
- - `opts.scanPeriod`: 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).
41
  - `opts.captureImage`: Whether to include the scanned image data as part of the scan result. See the `scan` event for format details. Default `false`.
 
 
 
42
 
43
- ### `scanner.start(camera)`
44
 
45
- - Start scanning using `camera` as the source. Returns promise.
46
- - `camera`: Instance of `Instascan.Camera` from `Instascan.Camera.getCameras`.
 
47
  - Continuation: `function ()`, called when camera is active and scanning has started.
48
 
49
- ### `scanner.stop()`
50
 
51
- - Stop scanning. This stops the camera as well.
 
52
 
53
- ### `scanner.addListener('scan', callback)`
54
 
55
- - Raised when a QR code is scanned using the camera.
 
 
 
 
 
 
 
 
56
  - `callback`: `function (content, image)`
57
  - `content`: Scanned content decoded from the QR code.
58
- - `image`: `null` if `scanner.captureImage` is `false`, otherwise, a base64-encoded [WebP](https://en.wikipedia.org/wiki/WebP)-compressed data URI of the camera frame used to decode the QR code.
59
 
60
- ### `scanner.addListener('active', callback)`
61
 
62
- - Raised when the scanner becomes active as the result of `scanner.start` or the tab gaining focus.
 
63
  - `callback`: `function ()`
64
 
65
- ### `scanner.addListener('inactive', callback)`
66
 
67
- - Raised when the scanner becomes inactive as the result of `scanner.stop` or the tab losing focus.
 
68
  - `callback`: `function ()`
69
 
70
- ### `Instascan.Camera.getCameras()`
71
 
72
  - Enumerate available video devices. Returns promise.
73
  - Continuation: `function (cameras)`, called when cameras are available.
74
  - `cameras`: Array of `Instascan.Camera` instances available for use.
75
 
76
- ### `camera.id`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
- - Unique camera ID. Assigned by the browser.
79
 
80
- ### `camera.name`
 
 
 
81
 
82
- - Camera name, including manufacturer and model, e.g. "Microsoft Lifecam HD-3000". Can be `null` if the user has not yet allowed camera access, e.g. on first launch of the app.
83
 
84
  ## Credits
85
 
86
- -- assets/qr.png
87
- -- assets/setup.jpg
1
+ # ![Instascan](https://raw.githubusercontent.com/schmich/instascan/master/assets/qr.png) Instascan
2
+ Real-time webcam-driven HTML5 QR code scanner.
3
+
4
+ ## Installing
5
+
6
+ *Note:* Chrome requires HTTPS when using the WebRTC API. Any pages using this library should be served over HTTPS.
7
+
8
+ ### NPM
9
+
10
+ `npm install --save instascan`
11
+
12
+ ```javascript
13
+ const Instascan = require('instascan');
14
+ ```
15
+
16
+ ### Bower
17
+
18
+ Pending. [Drop a note](https://github.com/schmich/instascan/issues/31) if you need Bower support.
19
+
20
+ ### Minified
21
+
22
+ Copy `instascan.min.js` from the [releases](https://github.com/schmich/instascan/releases) page and load with:
23
+
24
+ ```html
25
+ <script type="text/javascript" src="instascan.min.js"></script>
26
+ ```
27
 
28
  ## Example
29
 
32
  <html>
33
  <head>
34
  <title>Instascan</title>
35
+ <script type="text/javascript" src="instascan.min.js"></script>
36
  </head>
37
  <body>
38
  <video id="preview"></video>
39
  <script type="text/javascript">
40
+ let scanner = new Instascan.Scanner({ video: document.getElementById('preview') });
41
  scanner.addListener('scan', function (content, image) {
42
  console.log(content);
43
  });
54
 
55
  ## API
56
 
57
+ ### let scanner = new Instascan.Scanner(opts)
58
 
59
  - Create a new scanner with options.
60
+ - `opts.continuous`: Whether to scan continuously for QR codes. If `false`, use [`scanner.scan`](#let-result--scannerscan) to manually scan. Default `true`.
61
+ - `opts.video`: 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.
62
  - `opts.mirror`: Whether to horizontally mirror the video preview. This is helpful when trying to scan a QR code with a user-facing camera. Default `true`.
 
 
 
63
  - `opts.captureImage`: Whether to include the scanned image data as part of the scan result. See the `scan` event for format details. Default `false`.
64
+ - `opts.backgroundScan`: 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 `false`.
65
+ - `opts.refractoryPeriod`: Only applies to continuous mode. The period, in milliseconds, before the same QR code will be recognized in succession. Default `5000`.
66
+ - `opts.scanPeriod`: 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).
67
 
68
+ ### scanner.start(camera)
69
 
70
+ - Activate `camera` and start scanning using it as the source. Returns promise.
71
+ - This must be called in order to use [`scanner.scan`](#let-result--scannerscan) or receive [`scan`](#scanneraddlistenerscan-callback) events.
72
+ - `camera`: Instance of `Instascan.Camera` from [`Instascan.Camera.getCameras`](#instascancameragetcameras).
73
  - Continuation: `function ()`, called when camera is active and scanning has started.
74
 
75
+ ### scanner.stop()
76
 
77
+ - Stop scanning and deactivate the camera. Returns promise.
78
+ - Continuation: `function ()`, called when camera and scanning have stopped.
79
 
80
+ ### let result = scanner.scan()
81
 
82
+ - Scan video immediately for a QR code.
83
+ - QR codes recognized with this method are not raised via the `scan` event.
84
+ - If no QR code is detected, `result` is `null`.
85
+ - `result.content`: Scanned content decoded from the QR code.
86
+ - `result.image`: Undefined if [`scanner.captureImage`](#let-scanner--new-instascanscanneropts) is `false`, otherwise, see the [`scan`](#scanneraddlistenerscan-callback) event for format.
87
+
88
+ ### scanner.addListener('scan', callback)
89
+
90
+ - Raised when a QR code is scanned using the camera in continuous mode (see [`scanner.continuous`](#let-scanner--new-instascanscanneropts)).
91
  - `callback`: `function (content, image)`
92
  - `content`: Scanned content decoded from the QR code.
93
+ - `image`: `null` if [`scanner.captureImage`](#let-scanner--new-instascanscanneropts) is `false`, otherwise, a base64-encoded [WebP](https://en.wikipedia.org/wiki/WebP)-compressed data URI of the camera frame used to decode the QR code.
94
 
95
+ ### scanner.addListener('active', callback)
96
 
97
+ - Raised when the scanner becomes active as the result of [`scanner.start`](#scannerstartcamera) or the tab gaining focus.
98
+ - If `opts.video` element was specified, it will have the `active` CSS class.
99
  - `callback`: `function ()`
100
 
101
+ ### scanner.addListener('inactive', callback)
102
 
103
+ - Raised when the scanner becomes inactive as the result of [`scanner.stop`](#scannerstop) or the tab losing focus.
104
+ - If `opts.video` element was specified, it will have the `inactive` CSS class.
105
  - `callback`: `function ()`
106
 
107
+ ### Instascan.Camera.getCameras()
108
 
109
  - Enumerate available video devices. Returns promise.
110
  - Continuation: `function (cameras)`, called when cameras are available.
111
  - `cameras`: Array of `Instascan.Camera` instances available for use.
112
 
113
+ ### camera.id
114
+
115
+ - Unique camera ID provided by the browser.
116
+ - These IDs are stable and can be persisted across instances of your application (e.g. in localStorage).
117
+
118
+ ### camera.name
119
+
120
+ - Camera name, including manufacturer and model, e.g. "Microsoft LifeCam HD-3000".
121
+ - Can be `null` if the user has not yet allowed camera access, e.g. on first launch of the app.
122
+
123
+ ## Compatibility
124
+
125
+ Instascan works with [any browser that supports the getUserMedia API](http://caniuse.com/#feat=stream), which currently includes Chome, Firefox, Opera, and Edge. IE and Safari are not supported.
126
+
127
+ ## Performance
128
+
129
+ Many factors affect how quickly and reliably Instascan can detect QR codes.
130
+
131
+ If you control creation of the QR code, consider the following:
132
+
133
+ - A larger physical code is better. A 2" square code is better than a 1" square code.
134
+ - Flat, smooth, matte surfaces are better than curved, rough, glossy surfaces.
135
+ - 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.
136
+ - A simpler code is better. You can use [this QR code generator](https://www.the-qrcode-generator.com/) to see how your input affects complexity.
137
+ - For the same length, numeric content is simpler than ASCII content, which is simpler than Unicode content.
138
+ - Shorter content is simpler. If you're encoding a URL, consider using a shortener such as [goo.gl](https://goo.gl/) or [bit.ly](https://bitly.com/).
139
+
140
+ When scanning, consider the following:
141
+
142
+ - QR code orientation doesn't matter.
143
+ - Higher resolution video is better, but is more CPU intensive.
144
+ - Direct, orthogonal scanning is better than scanning at an angle.
145
+ - Blurry video greatly reduces scanner performance.
146
+ - 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.
147
+ - Exposure adjustment on cameras can cause lags in detection. Consider disabling it or having a fixed white backdrop.
148
 
149
+ ## Example Setup
150
 
151
+ - Purpose: To scan QR code stickers on paper cards and plastic bags.
152
+ - Camera: [Microsoft LifeCam HD-3000](http://www.newegg.com/Product/Product.aspx?Item=9SIA4RE40S4991), 720p, fixed focus, around $30 USD.
153
+ - Small support to ensure camera is focused on subject.
154
+ - White paper backdrop to mitigate exposure adjustment.
155
 
156
+ ![Setup](https://raw.githubusercontent.com/schmich/instascan/master/assets/setup.jpg)
157
 
158
  ## Credits
159
 
160
+ ++ assets/qr.png
161
+ ++ assets/setup.jpg
package.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "name": "instascan",
3
- "version": "0.0.3",
4
  "description": "Webcam-driven QR code scanner.",
5
  "main": "index.js",
6
  "scripts": {
@@ -21,7 +21,8 @@
21
  "response",
22
  "scan",
23
  "scanner",
24
- "webcam"
 
25
  ],
26
  "author": "Chris Schmich <schmch@gmail.com>",
27
  "license": "MIT",
1
  {
2
  "name": "instascan",
3
+ "version": "1.0.0",
4
  "description": "Webcam-driven QR code scanner.",
5
  "main": "index.js",
6
  "scripts": {
21
  "response",
22
  "scan",
23
  "scanner",
24
+ "webcam",
25
+ "realtime"
26
  ],
27
  "author": "Chris Schmich <schmch@gmail.com>",
28
  "license": "MIT",
src/scanner.js CHANGED
@@ -3,60 +3,82 @@ const ZXing = require('./zxing')();
3
  const Visibility = require('visibilityjs');
4
  const StateMachine = require('fsm-as-promised');
5
 
6
- class ActiveScan {
7
  constructor(emitter, analyzer, captureImage, scanPeriod, refractoryPeriod) {
8
- this.active = false;
9
  this.scanPeriod = scanPeriod;
10
- this.frameCount = 0;
11
- this.emitter = emitter;
12
- this.analyzer = analyzer;
13
  this.captureImage = captureImage;
14
  this.refractoryPeriod = refractoryPeriod;
 
 
 
 
 
15
  }
16
 
17
  start() {
18
- this.active = true;
19
  requestAnimationFrame(() => this._scan());
20
  }
21
 
22
  stop() {
23
- this.active = false;
24
  }
25
 
26
- _scan() {
27
- if (!this.active) {
28
- return;
29
- }
30
-
31
- requestAnimationFrame(() => this._scan());
32
-
33
- if (++this.frameCount !== this.scanPeriod) {
34
- return;
35
- } else {
36
- this.frameCount = 0;
37
- }
38
 
39
- let analysis = this.analyzer.analyze();
 
40
  if (!analysis) {
41
- return;
42
  }
43
 
44
  let { result, canvas } = analysis;
45
- if (!result || result === this.lastResult) {
46
- return;
 
 
 
 
47
  }
48
 
49
  clearTimeout(this.refractoryTimeout);
50
  this.refractoryTimeout = setTimeout(() => {
51
- this.lastResult = null;
52
  }, this.refractoryPeriod);
53
 
54
  let image = this.captureImage ? canvas.toDataURL('image/webp', 0.8) : null;
55
 
56
- this.lastResult = result;
57
- setTimeout(() => {
58
- this.emitter.emit('scan', result, image);
59
- }, 0);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  }
61
  }
62
 
@@ -116,7 +138,8 @@ class Analyzer {
116
 
117
  let data = this.canvasContext.getImageData(0, 0, this.sensorWidth, this.sensorHeight).data;
118
  for (var i = 0, j = 0; i < data.length; i += 4, j++) {
119
- ZXing.HEAPU8[this.imageBuffer + j] = data[i];
 
120
  }
121
 
122
  let err = ZXing._decode_qr(this.decodeCallback);
@@ -137,14 +160,19 @@ class Scanner extends EventEmitter {
137
  constructor(opts) {
138
  super();
139
 
140
- this._scan = null;
141
- this._camera = null;
142
- this.scanPeriod = opts.scanPeriod || 1;
143
- this.refractoryPeriod = opts.refractoryPeriod || (5 * 1000);
144
- this.captureImage = opts.captureImage || false;
145
- this.backgroundScan = opts.backgroundScan || false;
146
  this.video = this._configureVideo(opts);
147
- this.analyzer = new Analyzer(this.video);
 
 
 
 
 
 
 
 
 
 
 
148
 
149
  Visibility.change((e, state) => {
150
  if (state === 'visible') {
@@ -160,35 +188,23 @@ class Scanner extends EventEmitter {
160
  }
161
  });
162
 
163
- this._fsm = StateMachine.create({
164
- initial: 'stopped',
165
- events: [
166
- { name: 'start', from: 'stopped', to: 'started' },
167
- { name: 'stop', from: ['started', 'active', 'inactive'], to: 'stopped' },
168
- { name: 'activate', from: ['started', 'inactive'], to: 'active' },
169
- { name: 'deactivate', from: ['started', 'active'], to: 'inactive' }
170
- ],
171
- callbacks: {
172
- onleaveactive: () => {
173
- this._disableScan();
174
- this.emit('inactive');
175
- },
176
- onenteractive: async (options) => {
177
- if (Visibility.state() !== 'visible' && !this.backgroundScan) {
178
- return false;
179
- }
180
 
181
- return await this._enableScan(options.args[0]);
182
- },
183
- onenteredstarted: async (options) => {
184
- await this._fsm.activate(options.args[0]);
185
- }
186
- }
187
  });
188
 
189
  this.emit('inactive');
190
  }
191
 
 
 
 
 
192
  async start(camera = null) {
193
  if (this._fsm.can('start')) {
194
  await this._fsm.start(camera);
@@ -198,40 +214,93 @@ class Scanner extends EventEmitter {
198
  }
199
  }
200
 
201
- stop() {
202
  if (this._fsm.can('stop')) {
203
- this._fsm.stop();
204
  }
205
  }
206
 
207
- set camera(camera) {
208
- if (this._fsm.current === 'stopped' || this._fsm.current === 'inactive') {
209
- this._camera = camera;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  } else {
211
- this._fsm.stop();
212
- this._fsm.start(camera);
213
  }
214
  }
215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  async _enableScan(camera) {
217
  this._camera = camera || this._camera;
218
  if (!this._camera) {
219
- throw new Exception('Camera is not defined.');
220
  }
221
 
222
  let streamUrl = await this._camera.start();
223
  this.video.src = streamUrl;
224
- this._scan = new ActiveScan(this, this.analyzer, this.captureImage, this.scanPeriod, this.refractoryPeriod);
225
- this._scan.start();
226
- this.emit('active');
 
227
  }
228
 
229
  _disableScan() {
230
  this.video.src = '';
231
 
232
- if (this._scan) {
233
- this._scan.stop();
234
- this._scan = null;
235
  }
236
 
237
  if (this._camera) {
@@ -242,24 +311,63 @@ class Scanner extends EventEmitter {
242
  _configureVideo(opts) {
243
  if (opts.video) {
244
  if (opts.video.tagName !== 'VIDEO') {
245
- throw new Exception('Video must be a <video> element.');
246
  }
247
  }
248
 
249
  var video = opts.video || document.createElement('video');
250
  video.setAttribute('autoplay', 'autoplay');
251
 
252
- if (opts.mirror !== false && opts.video) {
253
- video.style.MozTransform = 'scaleX(-1)';
254
- video.style.webkitTransform = 'scaleX(-1)';
255
- video.style.OTransform = 'scaleX(-1)';
256
- video.style.msFilter = 'FlipH';
257
- video.style.filter = 'FlipH';
258
- video.style.transform = 'scaleX(-1)';
259
- }
260
-
261
  return video;
262
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
  }
264
 
265
  module.exports = Scanner;
3
  const Visibility = require('visibilityjs');
4
  const StateMachine = require('fsm-as-promised');
5
 
6
+ class ScanProvider {
7
  constructor(emitter, analyzer, captureImage, scanPeriod, refractoryPeriod) {
 
8
  this.scanPeriod = scanPeriod;
 
 
 
9
  this.captureImage = captureImage;
10
  this.refractoryPeriod = refractoryPeriod;
11
+ this._emitter = emitter;
12
+ this._frameCount = 0;
13
+ this._analyzer = analyzer;
14
+ this._lastResult = null;
15
+ this._active = false;
16
  }
17
 
18
  start() {
19
+ this._active = true;
20
  requestAnimationFrame(() => this._scan());
21
  }
22
 
23
  stop() {
24
+ this._active = false;
25
  }
26
 
27
+ scan() {
28
+ return this._analyze(false);
29
+ }
 
 
 
 
 
 
 
 
 
30
 
31
+ _analyze(skipDups) {
32
+ let analysis = this._analyzer.analyze();
33
  if (!analysis) {
34
+ return null;
35
  }
36
 
37
  let { result, canvas } = analysis;
38
+ if (!result) {
39
+ return null;
40
+ }
41
+
42
+ if (skipDups && result === this._lastResult) {
43
+ return null;
44
  }
45
 
46
  clearTimeout(this.refractoryTimeout);
47
  this.refractoryTimeout = setTimeout(() => {
48
+ this._lastResult = null;
49
  }, this.refractoryPeriod);
50
 
51
  let image = this.captureImage ? canvas.toDataURL('image/webp', 0.8) : null;
52
 
53
+ this._lastResult = result;
54
+
55
+ let payload = { content: result };
56
+ if (image) {
57
+ payload.image = image;
58
+ }
59
+
60
+ return payload;
61
+ }
62
+
63
+ _scan() {
64
+ if (!this._active) {
65
+ return;
66
+ }
67
+
68
+ requestAnimationFrame(() => this._scan());
69
+
70
+ if (++this._frameCount !== this.scanPeriod) {
71
+ return;
72
+ } else {
73
+ this._frameCount = 0;
74
+ }
75
+
76
+ let result = this._analyze(true);
77
+ if (result) {
78
+ setTimeout(() => {
79
+ this._emitter.emit('scan', result.content, result.image || null);
80
+ }, 0);
81
+ }
82
  }
83
  }
84
 
138
 
139
  let data = this.canvasContext.getImageData(0, 0, this.sensorWidth, this.sensorHeight).data;
140
  for (var i = 0, j = 0; i < data.length; i += 4, j++) {
141
+ let [r, g, b] = [data[i], data[i + 1], data[i + 2]];
142
+ ZXing.HEAPU8[this.imageBuffer + j] = Math.trunc((r + g + b) / 3);
143
  }
144
 
145
  let err = ZXing._decode_qr(this.decodeCallback);
160
  constructor(opts) {
161
  super();
162
 
 
 
 
 
 
 
163
  this.video = this._configureVideo(opts);
164
+ this.mirror = (opts.mirror !== false);
165
+ this.backgroundScan = opts.backgroundScan || false;
166
+ this._continuous = (opts.continuous !== false);
167
+ this._analyzer = new Analyzer(this.video);
168
+ this._camera = null;
169
+
170
+ let captureImage = opts.captureImage || false;
171
+ let scanPeriod = opts.scanPeriod || 1;
172
+ let refractoryPeriod = opts.refractoryPeriod || (5 * 1000);
173
+
174
+ this._scanner = new ScanProvider(this, this._analyzer, captureImage, scanPeriod, refractoryPeriod);
175
+ this._fsm = this._createStateMachine();
176
 
177
  Visibility.change((e, state) => {
178
  if (state === 'visible') {
188
  }
189
  });
190
 
191
+ this.addListener('active', () => {
192
+ this.video.classList.remove('inactive');
193
+ this.video.classList.add('active');
194
+ });
 
 
 
 
 
 
 
 
 
 
 
 
 
195
 
196
+ this.addListener('inactive', () => {
197
+ this.video.classList.remove('active');
198
+ this.video.classList.add('inactive');
 
 
 
199
  });
200
 
201
  this.emit('inactive');
202
  }
203
 
204
+ scan() {
205
+ return this._scanner.scan();
206
+ }
207
+
208
  async start(camera = null) {
209
  if (this._fsm.can('start')) {
210
  await this._fsm.start(camera);
214
  }
215
  }
216
 
217
+ async stop() {
218
  if (this._fsm.can('stop')) {
219
+ await this._fsm.stop();
220
  }
221
  }
222
 
223
+ set captureImage(capture) {
224
+ this._scanner.captureImage = capture;
225
+ }
226
+
227
+ get captureImage() {
228
+ return this._scanner.captureImage;
229
+ }
230
+
231
+ set scanPeriod(period) {
232
+ this._scanner.scanPeriod = period;
233
+ }
234
+
235
+ get scanPeriod() {
236
+ return this._scanner.scanPeriod;
237
+ }
238
+
239
+ set refractoryPeriod(period) {
240
+ this._scanner.refractoryPeriod = period;
241
+ }
242
+
243
+ get refractoryPeriod() {
244
+ return this._scanner.refractoryPeriod;
245
+ }
246
+
247
+ set continuous(continuous) {
248
+ this._continuous = continuous;
249
+
250
+ if (continuous && this._fsm.current === 'active') {
251
+ this._scanner.start();
252
  } else {
253
+ this._scanner.stop();
 
254
  }
255
  }
256
 
257
+ get continuous() {
258
+ return this._continuous;
259
+ }
260
+
261
+ set mirror(mirror) {
262
+ this._mirror = mirror;
263
+
264
+ if (mirror) {
265
+ this.video.style.MozTransform = 'scaleX(-1)';
266
+ this.video.style.webkitTransform = 'scaleX(-1)';
267
+ this.video.style.OTransform = 'scaleX(-1)';
268
+ this.video.style.msFilter = 'FlipH';
269
+ this.video.style.filter = 'FlipH';
270
+ this.video.style.transform = 'scaleX(-1)';
271
+ } else {
272
+ this.video.style.MozTransform = null;
273
+ this.video.style.webkitTransform = null;
274
+ this.video.style.OTransform = null;
275
+ this.video.style.msFilter = null;
276
+ this.video.style.filter = null;
277
+ this.video.style.transform = null;
278
+ }
279
+ }
280
+
281
+ get mirror() {
282
+ return this._mirror;
283
+ }
284
+
285
  async _enableScan(camera) {
286
  this._camera = camera || this._camera;
287
  if (!this._camera) {
288
+ throw new Error('Camera is not defined.');
289
  }
290
 
291
  let streamUrl = await this._camera.start();
292
  this.video.src = streamUrl;
293
+
294
+ if (this._continuous) {
295
+ this._scanner.start();
296
+ }
297
  }
298
 
299
  _disableScan() {
300
  this.video.src = '';
301
 
302
+ if (this._scanner) {
303
+ this._scanner.stop();
 
304
  }
305
 
306
  if (this._camera) {
311
  _configureVideo(opts) {
312
  if (opts.video) {
313
  if (opts.video.tagName !== 'VIDEO') {
314
+ throw new Error('Video must be a <video> element.');
315
  }
316
  }
317
 
318
  var video = opts.video || document.createElement('video');
319
  video.setAttribute('autoplay', 'autoplay');
320
 
 
 
 
 
 
 
 
 
 
321
  return video;
322
  }
323
+
324
+ _createStateMachine() {
325
+ return StateMachine.create({
326
+ initial: 'stopped',
327
+ events: [
328
+ {
329
+ name: 'start',
330
+ from: 'stopped',
331
+ to: 'started'
332
+ },
333
+ {
334
+ name: 'stop',
335
+ from: ['started', 'active', 'inactive'],
336
+ to: 'stopped'
337
+ },
338
+ {
339
+ name: 'activate',
340
+ from: ['started', 'inactive'],
341
+ to: ['active', 'inactive'],
342
+ condition: function (options) {
343
+ if (Visibility.state() === 'visible' || this.backgroundScan) {
344
+ return 'active';
345
+ } else {
346
+ return 'inactive';
347
+ }
348
+ }
349
+ },
350
+ {
351
+ name: 'deactivate',
352
+ from: ['started', 'active'],
353
+ to: 'inactive'
354
+ }
355
+ ],
356
+ callbacks: {
357
+ onenteractive: async (options) => {
358
+ await this._enableScan(options.args[0]);
359
+ this.emit('active');
360
+ },
361
+ onleaveactive: () => {
362
+ this._disableScan();
363
+ this.emit('inactive');
364
+ },
365
+ onenteredstarted: async (options) => {
366
+ await this._fsm.activate(options.args[0]);
367
+ }
368
+ }
369
+ });
370
+ }
371
  }
372
 
373
  module.exports = Scanner;

Readme

Instascan

Real-time webcam-driven HTML5 QR code scanner.

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

var 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">
      var scanner = new Instascan.Scanner({ video: document.getElementById('preview') });
      scanner.addListener('scan', function (content, image) {
        console.log(content);
      });

      Instascan.Camera.getCameras().then(function (cameras) {
        if (cameras.length > 0) {
          scanner.start(cameras[0]);
        }
      });
    </script>
  </body>
</html>

API

var scanner = new Instascan.Scanner(opts)

  • Create a new scanner with options.
  • opts.continuous: Whether to scan continuously for QR codes. If false, use scanner.scan to manually scan. Default true.
  • opts.video: 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.
  • opts.mirror: Whether to horizontally mirror the video preview. This is helpful when trying to scan a QR code with a user-facing camera. Default true.
  • opts.captureImage: Whether to include the scanned image data as part of the scan result. See the scan event for format details. Default false.
  • opts.backgroundScan: 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 false.
  • opts.refractoryPeriod: Only applies to continuous mode. The period, in milliseconds, before the same QR code will be recognized in succession. Default 5000.
  • opts.scanPeriod: 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).

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.
  • Continuation: function (), called when camera is active and scanning has started.

scanner.stop()

  • Stop scanning and deactivate the camera. Returns promise.
  • Continuation: function (), called when camera and scanning have stopped.

var result = scanner.scan()

  • Scan video immediately for a QR code.
  • QR codes recognized with this method are not raised 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)

  • Raised 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)

  • Raised 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)

  • Raised 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.
  • Continuation: function (cameras), called when cameras are available.
  • cameras: Array of Instascan.Camera instances available for use.

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".
  • Can be null if the user has not yet allowed camera access, e.g. on first launch of the app.

Compatibility

Instascan works with any browser that supports the getUserMedia API, which currently includes Chome, Firefox, Opera, and Edge. IE and Safari are not supported.

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.

Credits

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

License

Copyright © 2016 Chris Schmich <br /> MIT License. See LICENSE for details.