UNPKG

29.2 kBMarkdownView Raw
1# Html5-QRCode
2## (supports barcodes now :))
3A cross-platform HTML5 QR code & barcode reader.
4
5Use this lightweight library to easily / quickly integrate QR code, bar code, and other common code scanning capabilities to your web application.
6- Supports easy scanning using an integrated webcam or camera in smartphones (Android / IOS).
7
8- Supports scanning codes from files or default cameras on smartphones.
9
10- **<u>Recently Added</u>** Supports bar code scanning in various formats.
11
12- Supports two kind of APIs
13 - `Html5QrcodeScanner` - End-to-end scanner with UI, integrate with less than ten lines of code.
14 - `Html5Qrcode` - Powerful set of APIs you can use to build your UI without worrying about camera setup, handling permissions, reading codes, etc.
15
16> Support for scanning local files on the device is a new addition and helpful for the web browser which does not support inline web-camera access in smartphones. **Note:** This doesn't upload files to any server - everything is done locally.
17
18[![Build Status](https://travis-ci.org/mebjas/html5-qrcode.svg?branch=master)](https://travis-ci.org/mebjas/html5-qrcode) [![GitHub issues](https://img.shields.io/github/issues/mebjas/html5-qrcode)](https://github.com/mebjas/html5-qrcode/issues) [![GitHub tag (latest by date)](https://img.shields.io/github/v/tag/mebjas/html5-qrcode)](https://github.com/mebjas/html5-qrcode/releases) ![GitHub](https://img.shields.io/github/license/mebjas/html5-qrcode)
19
20[![npm](https://nodei.co/npm/html5-qrcode.png)](https://www.npmjs.com/package/html5-qrcode)
21
22| <img src="./assets/pixel3.gif" width="200px"> | <img src="./assets/pixel4_barcode_480.gif" width="180px">|
23| -- | -- |
24| _Figure: Running on Android, Pixel 3_ | _Figure: Running on Android, Pixel 4, **Scanning different types of codes**_ |
25
26## Notice
27**UX/UXD/UXR help wanted**: We are looking to improve user experience of this code scanning library - if you are interested in making this experience better for both developers and end users, please share your ideas, thoughts, inputs in [this discussion](https://github.com/mebjas/html5-qrcode/discussions/213)
28
29## Supported platforms
30We are working continuously on adding support for more and more platforms. If you find a platform or a browser where the library is not working, please feel free to file an issue. Check the [demo link](https://blog.minhazav.dev/research/html5-qrcode.html) to test it out.
31
32**Legends**
33- ![](assets/done.png) Means full support - inline webcam and file based
34- ![](assets/partial.png) Means partial support - only file based, webcam in progress
35
36### PC / Mac
37
38| <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png" alt="Firefox" width="24px" height="24px" /><br/>Firefox | <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png" alt="Chrome" width="24px" height="24px" /><br/>Chrome | <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari/safari_48x48.png" alt="Safari" width="24px" height="24px" /><br/>Safari | <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/opera/opera_48x48.png" alt="Opera" width="24px" height="24px" /><br/>Opera | <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/edge/edge_48x48.png" alt="Edge" width="24px" height="24px" /><br/> Edge
39| --------- | --------- | --------- | --------- | ------- |
40|![](./assets/done.png)| ![](assets/done.png)| ![](assets/done.png)| ![](assets/done.png) | ![](assets/done.png)
41
42### Android
43
44| <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png" alt="Chrome" width="24px" height="24px" /><br/>Chrome | <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png" alt="Firefox" width="24px" height="24px" /><br/>Firefox | <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/edge/edge_48x48.png" alt="Edge" width="24px" height="24px" /><br/> Edge | <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/opera/opera_48x48.png" alt="Opera" width="24px" height="24px" /><br/>Opera | <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/opera-mini/opera-mini_48x48.png" alt="Opera-Mini" width="24px" height="24px" /><br/> Opera Mini | <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/uc/uc_24x24.png" alt="UC" width="24px" height="24px" /> <br/> UC
45| --------- | --------- | --------- | --------- | --------- | --------- |
46|![](./assets/done.png)| ![](assets/done.png)| ![](assets/done.png)| ![](assets/done.png)| ![](assets/partial.png) | ![](assets/partial.png)
47
48### IOS
49
50| <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari-ios/safari-ios_24x24.png" alt="Safari" width="24px" height="24px" /><br/>Safari | <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png" alt="Chrome" width="24px" height="24px" /><br/>Chrome | <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png" alt="Firefox" width="24px" height="24px" /><br/>Firefox | <img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/edge/edge_48x48.png" alt="Edge" width="24px" height="24px" /><br/> Edge
51| --------- | --------- | --------- | --------- |
52|![](./assets/done.png)| ![](assets/partial.png)| ![](assets/partial.png)| ![](assets/partial.png)
53
54> Apparently, Webkit for IOS is used by Chrome, Firefox, and other browsers in IOS and they do not have webcam permissions yet. There is an ongoing issue on fixing the support for iOS - [issue/14](https://github.com/mebjas/html5-qrcode/issues/14)
55
56### Framework support
57The library can be easily used with several other frameworks, I have been adding examples for a few of them and would continue to add more.
58
59|<img src="./assets/html5.png" width="30px">| <img src="./assets/vuejs.png" width="30px">|<img src="./assets/electron.png" width="30px"> | <img src="./assets/react.svg" width="30px">
60| -------- | -------- | -------- | -------- |
61| [Html5](./examples/html5) | [VueJs](./examples/vuejs) | [ElectronJs](./examples/electron) | [React](./examples/react)
62
63### Supported Code formats
64Code scanning is dependent on [Zxing-js](https://github.com/zxing-js/library) library. We will be working on top of it to add support for more types of code scanning. If you feel a certain type of code would be helpful to have, please file a feature request.
65
66| Code | Example |
67| ---- | ----- |
68| QR Code | <img src="./assets/qr-code.png" width="200px"> |
69| AZTEC | <img src="./assets/aztec.png" > |
70| CODE_39| <img src="./assets/code_39.gif" > |
71| CODE_93| <img src="./assets/code_93.gif" >|
72| CODE_128| <img src="./assets/code_128.gif" >|
73| MAXICODE| <img src="./assets/maxicode.gif" > |
74| ITF| <img src="./assets/itf.png" >|
75| EAN_13|<img src="./assets/ean13.jpeg" > |
76| EAN_8| <img src="./assets/ean8.jpeg" >|
77| PDF_417| <img src="./assets/pdf417.png" >|
78| RSS_14| <img src="./assets/rss14.gif" >|
79| RSS_EXPANDED|<img src="./assets/rssexpanded.gif" > |
80| UPC_A| <img src="./assets/upca.jpeg" >|
81| UPC_E| <img src="./assets/upce.jpeg" >|
82| DATA_MATRIX|<img src="./assets/datamatrix.png" > |
83
84## Description - [View Demo](https://blog.minhazav.dev/research/html5-qrcode.html)
85
86This is a cross-platform Javascript library to integrate QR code, bar codes & a few other types of code scanning capabilities to your applications running on HTML5 compatible browser.
87
88Supports:
89- Querying camera on the device (with user permissions)
90- Rendering live camera feed, with easy to use user interface for scanning
91- Supports scanning a different kind of QR codes, bar codes and other formats
92- Supports selecting image files from the device for scanning codes
93
94## How to use?
95> For full information [read this article](https://blog.minhazav.dev/HTML5-QR-Code-scanning-launched-v1.0.1/).
96
97Download the script from [release page](https://github.com/mebjas/html5-qrcode/releases) or `npm` with:
98```
99npm i html5-qrcode
100```
101
102Add an element you want to use as a placeholder for QR Code scanner
103```html
104<div id="reader" width="600px"></div>
105```
106> Ideally do not set the height of this container as the height should depend on the height of the video feed from the camera. The library would honor the existing width, otherwise apply the default width. The height is derived from the aspect ratio of the video feed.
107
108Add `minified/html5-qrcode.min.js` in your web page.
109> I would recommend using the minified version as it's transformed to standard javascript. The `html5-qrcode.js` is written with ECMAScript and may not be supported in the older version of the browsers. I wrote in this as it's easier to maintain!
110
111```html
112<script src="./minified/html5-qrcode.js"></script>
113<!--
114 Or use directly from Github
115
116<script src="https://raw.githubusercontent.com/mebjas/html5-qrcode/master/minified/html5-qrcode.min.js"></script>
117-->
118```
119
120### Easy Mode - With end to end scanner user interface
121`Html5QrcodeScanner` lets you implement an end to end scanner with few lines of code with the default user interface which allows scanning using the camera or selecting an image from the file system.
122
123You can setup the scanner as follows:
124```js
125function onScanSuccess(decodedText, decodedResult) {
126 // handle the scanned code as you like, for example:
127 console.log(`Code matched = ${decodedText}`, decodedResult);
128}
129
130function onScanFailure(error) {
131 // handle scan failure, usually better to ignore and keep scanning.
132 // for example:
133 console.warn(`Code scan error = ${error}`);
134}
135
136let html5QrcodeScanner = new Html5QrcodeScanner(
137 "reader", { fps: 10, qrbox: 250 }, /* verbose= */ false);
138html5QrcodeScanner.render(onScanSuccess, onScanFailure);
139```
140
141### Pro Mode - if you want to implement your own user interface
142You can use `Html5Qrcode` class to set up your QR code scanner (with your own user interface) and allow users to scan QR codes using the camera or by choosing an image file in the file system or native cameras in smartphones.
143
144You can use the following APIs to `fetch camera`, `start` scanning and `stop` scanning.
145
146#### For using inline QR Code scanning with Webcam or Smartphone camera
147
148##### Start Scanning
149To get a list of supported cameras, query it using static method `Html5Qrcode.getCameras()`. This method returns a `Promise` with a list of devices supported in format `{ id: "id", label: "label" }`.
150```js
151// This method will trigger user permissions
152Html5Qrcode.getCameras().then(devices => {
153 /**
154 * devices would be an array of objects of type:
155 * { id: "id", label: "label" }
156 */
157 if (devices && devices.length) {
158 var cameraId = devices[0].id;
159 // .. use this to start scanning.
160 }
161}).catch(err => {
162 // handle err
163});
164```
165
166**Important**: Note that this method will trigger user permission if the user has not granted it already.
167> Warning: Direct access to the camera is a powerful feature. It requires consent from the user, and your site MUST be on a secure origin (HTTPS).
168>
169> Warning: Asking for access to the camera on page load will result in most of your users rejecting access to it. [More info](https://developers.google.com/web/fundamentals/media/capturing-images)
170
171Once you have the camera id from `device.id`, start camera using `Html5Qrcode#start(..)`. This method returns a `Promise` with Qr code scanning initiation.
172```js
173const html5QrCode = new Html5Qrcode(/* element id */ "reader");
174html5QrCode.start(
175 cameraId,
176 {
177 fps: 10, // Optional, frame per seconds for qr code scanning
178 qrbox: 250 // Optional, if you want bounded box UI
179 },
180 (decodedText, decodedResult) => {
181 // do something when code is read
182 },
183 (errorMessage) => {
184 // parse error, ignore it.
185 })
186.catch((err) => {
187 // Start failed, handle it.
188});
189```
190
191> You can optionally set another argument in constructor called `verbose` to print all logs to console
192
193```js
194const html5QrCode = new Html5Qrcode("reader", /* verbose= */ true);
195```
196
197##### Scanning without cameraId
198In mobile devices you may want users to directly scan the QR code using the back camera or the front camera for some use cases. For such cases you can avoid using the exact camera device id that you get from `Html5Qrcode.getCameras()`. The `start()` method allows passing constraints in place of camera device id similar to [html5 web API syntax](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). You can start scanning like mentioned in these examples:
199
200```js
201const html5QrCode = new Html5Qrcode("reader");
202const qrCodeSuccessCallback = (decodedText, decodedResult) => {
203 /* handle success */
204};
205const config = { fps: 10, qrbox: 250 };
206
207// If you want to prefer front camera
208html5QrCode.start({ facingMode: "user" }, config, qrCodeSuccessCallback);
209
210// If you want to prefer back camera
211html5QrCode.start({ facingMode: "environment" }, config, qrCodeSuccessCallback);
212
213// Select front camera or fail with `OverconstrainedError`.
214html5QrCode.start({ facingMode: { exact: "user"} }, config, qrCodeSuccessCallback);
215
216// Select back camera or fail with `OverconstrainedError`.
217html5QrCode.start({ facingMode: { exact: "environment"} }, config, qrCodeSuccessCallback);
218```
219
220Passing the `cameraId` (recommended appraoch) is similar to
221```js
222html5QrCode.start({ deviceId: { exact: cameraId} }, config, qrCodeSuccessCallback);
223```
224
225##### Stop Scanning
226
227To stop using camera and thus stop scanning, call `Html5Qrcode#stop()` which returns a `Promise` for stopping the video feed and scanning.
228```js
229html5QrCode.stop().then((ignore) => {
230 // QR Code scanning is stopped.
231}).catch((err) => {
232 // Stop failed, handle it.
233});
234```
235
236> Note that the class is stateful and `stop()` should be called to properly tear down the video and camera objects safely after calling `start()` when the scan is over or the user intend to move on. `stop()` will stop the video feed on the viewfinder.
237
238#### For QR Code scanning using local files or inbuild camera on Smartphones
239| Selector in Android | Selector in IOS|
240|------|-------|
241| Taken on Pixel 3, Google Chrome<br><img src="./assets/selector_android.png" width="300px"> | Taken on iPhone 7, Google Chrome<br><img src="./assets/selector_iphone.jpg" width="300px"> |
242
243You can alternatively leverage QR Code scanning for local files on the device or default camera on the device. It works similar to inline QR Code scanning.
244
245Define the HTML container and import the javascript library as mentioned above
246```html
247<div id="reader" width="600px" height="600px"></div>
248<script src="./minified/html5-qrcode.js"></script>
249```
250> It's not mandatory to set the height and width of the HTML element. If provided, the library would try to honor it. If it's not set, the library would set a default width and derive the height based on the input image's aspect ratio.
251
252Add an `Input` element for supporting file selection like this:
253```html
254<input type="file" id="qr-input-file" accept="image/*">
255<!--
256 Or add captured if you only want to enable smartphone camera, PC browsers will ignore it.
257-->
258
259<input type="file" id="qr-input-file" accept="image/*" capture>
260```
261Find more information about this at [developers.google.com](https://developers.google.com/web/fundamentals/media/capturing-images).
262
263And in javascript code initialize the object and attach listener like this:
264```js
265const html5QrCode = new Html5Qrcode(/* element id */ "reader");
266// File based scanning
267const fileinput = document.getElementById('qr-input-file');
268fileinput.addEventListener('change', e => {
269 if (e.target.files.length == 0) {
270 // No file selected, ignore
271 return;
272 }
273
274 const imageFile = e.target.files[0];
275 // Scan QR Code
276 html5QrCode.scanFile(imageFile, true)
277 .then(decodedText => {
278 // success, use decodedText
279 console.log(decodedText);
280 })
281 .catch(err => {
282 // failure, handle it.
283 console.log(`Error scanning file. Reason: ${err}`)
284 });
285});
286
287// Note: Current public API `scanFile` only returns the decoded text. There is
288// another work in progress API (in beta) which returns a full decoded result of
289// type `QrcodeResult` (check interface in src/core.ts) which contains the
290// decoded text, code format, code bounds, etc.
291// Eventually, this beta API will be migrated to the public API.
292```
293
294> Note that inline scanning and file-based scanning are mutually exclusive at the moment. This means you can only use one of them at a time. I'll soon be adding support for the option to have both if the requirement comes in. If you want to use both, use `html5QrCode#clear()` method to clear the canvas.
295
296## Demo
297<img src="./assets/qr-code.png" width="200px"><br>
298_Scan this image or visit [blog.minhazav.dev/research/html5-qrcode.html](https://blog.minhazav.dev/research/html5-qrcode.html)_
299
300### For more information
301Check these articles on how to use this library:
302- [HTML5 QR Code scanning - launched v1.0.1 without jQuery dependency and refactored Promise based APIs](https://blog.minhazav.dev/HTML5-QR-Code-scanning-launched-v1.0.1/).
303- [HTML5 QR Code scanning with javascript - Support for scanning the local file and using default camera added (v1.0.5)](https://blog.minhazav.dev/HTML5-QR-Code-scanning-support-for-local-file-and-default-camera/)
304
305## Screenshots
306![screenshot](assets/screen.gif)<br>
307_Figure: Screenshot from Google Chrome running on Macbook Pro_
308
309## Documentation
310Following methods are available in this library (typescript definition)
311
312```ts
313/** Camera Device interface. */
314interface CameraDevice {
315 id: string;
316 label: string;
317}
318
319/**
320 * Code formats supported by this library.
321 */
322enum Html5QrcodeSupportedFormats {
323 QR_CODE = 0,
324 AZTEC,
325 CODABAR,
326 CODE_39,
327 CODE_93,
328 CODE_128,
329 DATA_MATRIX,
330 MAXICODE,
331 ITF,
332 EAN_13,
333 EAN_8,
334 PDF_417,
335 RSS_14,
336 RSS_EXPANDED,
337 UPC_A,
338 UPC_E,
339 UPC_EAN_EXTENSION,
340}
341
342/** Format of detected code. */
343class QrcodeResultFormat {
344 public readonly format: Html5QrcodeSupportedFormats;
345 public readonly formatName: string;
346}
347
348/** Detailed scan result. */
349interface QrcodeResult {
350 /** Decoded text. */
351 text: string;
352
353 /** Format that was successfully scanned. */
354 format?: QrcodeResultFormat,
355}
356
357/** QrCode result object. */
358interface Html5QrcodeResult {
359 decodedText: string;
360 result: QrcodeResult;
361}
362
363/** Type for a callback for a successful code scan. */
364type QrcodeSuccessCallback
365 = (decodedText: string, result: Html5QrcodeResult) => void;
366
367/** Type for a callback for failure during code scan. */
368type QrcodeErrorCallback
369 = (errorMessage: string, error: Html5QrcodeError) => void;
370
371/**
372 * Interface for configuring {@class Html5Qrcode} class instance.
373 */
374interface Html5QrcodeConfigs {
375 /**
376 * Array of formats to support of type {@type Html5QrcodeSupportedFormats}.
377 */
378 formatsToSupport: Array<Html5QrcodeSupportedFormats> | undefined;
379}
380
381/** Configuration for creating {@class Html5Qrcode}. */
382interface Html5QrcodeFullConfig extends Html5QrcodeConfigs {
383 /**
384 * If true, all logs would be printed to console. False by default.
385 */
386 verbose: boolean | undefined;
387}
388
389interface Html5QrcodeCameraScanConfig {
390 /**
391 * Optional, Expected framerate of QR code scanning. example { fps: 2 } means the
392 * scanning would be done every 500 ms.
393 */
394 fps: number | undefined;
395
396 /**
397 * Optional, width of scanning region box, this should be smaller than the
398 * width and height of the full region.
399 * This would make the scanner look like this:
400 * ----------------------
401 * |********************|
402 * |******,,,,,,,,,*****| <--- shaded region
403 * |******| |*****| <--- non shaded region would be
404 * |******| |*****| used for QR code scanning.
405 * |******|_______|*****|
406 * |********************|
407 * |********************|
408 * ----------------------
409 */
410 qrbox?: number | undefined;
411
412 /**
413 * Optional, Desired aspect ratio for the video feed. Ideal aspect ratios
414 * are 4:3 or 16:9. Passing very wrong aspect ratio could lead to video feed
415 * not showing up.
416 */
417 aspectRatio?: number | undefined;
418
419 /**
420 * Optional, if {@code true} flipped QR Code won't be scanned. Only use this
421 * if you are sure the camera cannot give mirrored feed if you are facing
422 * performance constraints.
423 */
424 disableFlip?: boolean | undefined;
425
426 /**
427 * Optional, @beta(this config is not well supported yet).
428 *
429 * Important: When passed this will override other parameters like
430 * 'cameraIdOrConfig' or configurations like 'aspectRatio'.
431 * 'videoConstraints' should be of type {@code MediaTrackConstraints} as
432 * defined in
433 * https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints
434 * and is used to specify a variety of video or camera controls like:
435 * aspectRatio, facingMode, frameRate, etc.
436 */
437 videoConstraints?: MediaTrackConstraints | undefined;
438}
439
440/**
441 * Interface for controlling different aspects of {@class Html5QrcodeScanner}.
442 */
443interface Html5QrcodeScannerConfig
444 extends Html5QrcodeCameraScanConfig, Html5QrcodeConfigs {};
445
446class Html5Qrcode {
447 /**
448 * Returns a Promise with a list of all cameras supported by the device.
449 */
450 static getCameras(): Array<CameraDevice> // Returns a Promise
451
452 /**
453 * Initialize QR Code scanner.
454 *
455 * @param elementId - Id of the HTML element.
456 * @param verbose - optional configuration object
457 */
458 constructor(elementId: string, config: Html5QrcodeFullConfig | undefined) {}
459
460 /**
461 * Start scanning QR codes or barcodes for a given camera.
462 *
463 * @param cameraIdOrConfig Identifier of the camera, it can either be the
464 * camera id retrieved from {@code Html5Qrcode#getCameras()} method or
465 * object with facing mode constraint.
466 * @param configuration Extra configurations to tune the code scanner.
467 * @param qrCodeSuccessCallback Callback called when an instance of a QR
468 * code or any other supported bar code is found.
469 * @param qrCodeErrorCallback Callback called in cases where no instance of
470 * QR code or any other supported bar code is found.
471 */
472 start(
473 cameraIdOrConfig: Html5QrcodeIdentifier,
474 configuration: Html5QrcodeCameraScanConfig | undefined,
475 qrCodeSuccessCallback: QrcodeSuccessCallback | undefined,
476 qrCodeErrorCallback: QrcodeErrorCallback | undefined,
477 ): Promise<null> {}ass
478
479 /**
480 * Stops streaming QR Code video and scanning.
481 */
482 stop(): Promise<void> {}
483
484 /**
485 * Scans an Image File for QR Code.
486 *
487 * This feature is mutually exclusive to camera-based scanning, you should
488 * call stop() if the camera-based scanning was ongoing.
489 *
490 * @param imageFile a local file with Image content.
491 * @param showImage if true, the Image will be rendered on given element.
492 *
493 * @returns Promise with decoded QR code string on success.
494 */
495 scanFile(
496 imageFile: File,
497 /* default=true */ showImage: boolean | undefined): Promise<string> {}
498
499 /**
500 * Clears the existing canvas.
501 *
502 * Note: in case of ongoing web-cam based scan, it needs to be explicitly
503 * closed before calling this method, else it will throw an exception.
504 */
505 clear(): void {} // Returns void
506}
507
508class Html5QrcodeScanner {
509 /**
510 * Creates an instance of this class.
511 *
512 * @param elementId Id of the HTML element.
513 * @param config Extra configurations to tune the code scanner.
514 * @param verbose - If true, all logs would be printed to console.
515 */
516 constructor(
517 elementId: string,
518 config: Html5QrcodeScannerConfig | undefined,
519 verbose: boolean | undefined) {}
520
521 /**
522 * Renders the User Interface.
523 *
524 * @param qrCodeSuccessCallback Callback called when an instance of a QR
525 * code or any other supported bar code is found.
526 * @param qrCodeErrorCallback optional callback called in cases where no
527 * instance of QR code or any other supported bar code is found.
528 */
529 render(
530 qrCodeSuccessCallback: QrcodeSuccessCallback,
531 qrCodeErrorCallback: QrcodeErrorCallback | undefined) {}
532
533 /** Removes the QR Code scanner. */
534 clear(): Promise<void> {}
535}
536```
537
538### Extra optional `configuration` in `start()` method
539Configuration object that can be used to configure both the scanning behavior and the user interface (UI). Most of the fields have default properties that will be used unless a different value is provided. If you do not want to override anything, you can just pass in an empty object `{}`.
540
541#### `fps` - Integer, Example = 10
542A.K.A frame per second, the default value for this is 2 but it can be increased to get faster scanning. Increasing too high value could affect performance. Value `>1000` will simply fail.
543
544#### `qrbox` - Integer, Example = 250
545Use this property to limit the region of the viewfinder you want to use for scanning. The rest of the viewfinder would be shaded. For example, by passing config `{ qrbox : 250 }`, the screen will look like:
546
547<img src="./assets/screen.gif">
548
549#### `aspectRatio` - Float, Example 1.777778 for 16:9 aspect ratio
550Use this property to render the video feed in a certain aspect ratio. Passing a nonstandard aspect ratio like `100000:1` could lead to the video feed not even showing up. Ideal values can be:
551| Value | Aspect Ratio | Use Case |
552| ----- | ------------ | -------- |
553|1.333334 | 4:3 | Standard camera aspect ratio |
554|1.777778 | 16:9 | Fullscreen, cinematic |
555|1.0 | 1:1 | Square view |
556
557If you do not pass any value, the whole viewfinder would be used for scanning.
558**Note**: this value has to be smaller than the width and height of the `QR code HTML element`.
559
560#### `disableFlip` - Boolean (Optional), default = false
561By default, the scanner can scan for horizontally flipped QR Codes. This also enables scanning QR code using the front camera on mobile devices which are sometimes mirrored. This is `false` by default and I recommend changing this only if:
562- You are sure that the camera feed cannot be mirrored (Horizontally flipped)
563- You are facing performance issues with this enabled.
564
565Here's an example of a normal and mirrored QR Code
566| Normal QR Code | Mirrored QR Code |
567| ----- | ---- |
568| <img src="./assets/qr-code.png" width="200px"> | <img src="./assets/qr-code-flipped.png" width="200px"><br> |
569
570### Scanning only specific formats
571By default, both camera stream and image files are scanned against all the
572supported code formats. Both `Html5QrcodeScanner` and `Html5Qrcode` classes can
573 be configured to only support a subset of supported formats. Supported formats
574are defined in
575[enum Html5QrcodeSupportedFormats](https://github.com/mebjas/html5-qrcode/blob/master/src/core.ts#L14).
576
577```ts
578enum Html5QrcodeSupportedFormats {
579 QR_CODE = 0,
580 AZTEC,
581 CODABAR,
582 CODE_39,
583 CODE_93,
584 CODE_128,
585 DATA_MATRIX,
586 MAXICODE,
587 ITF,
588 EAN_13,
589 EAN_8,
590 PDF_417,
591 RSS_14,
592 RSS_EXPANDED,
593 UPC_A,
594 UPC_E,
595 UPC_EAN_EXTENSION,
596}
597```
598
599I recommend using this only if you need to explicitly omit support for certain
600formats or want to reduce the number of scans done per second for performance
601reasons.
602
603#### Scanning only QR code with `Html5Qrcode`
604```js
605const html5QrCode = new Html5Qrcode(
606 "reader", { formatsToSupport: [ Html5QrcodeSupportedFormats.QR_CODE ] });
607const qrCodeSuccessCallback = (decodedText, decodedResult) => {
608 /* handle success */
609};
610const config = { fps: 10, qrbox: 250 };
611
612// If you want to prefer front camera
613html5QrCode.start({ facingMode: "user" }, config, qrCodeSuccessCallback);
614```
615
616#### Scaning only QR code and UPC codes with `Html5QrcodeScanner`
617```js
618function onScanSuccess(decodedText, decodedResult) {
619 // Handle the scanned code as you like, for example:
620 console.log(`Code matched = ${decodedText}`, decodedResult);
621}
622
623const formatsToSupport = [
624 Html5QrcodeSupportedFormats.QR_CODE,
625 Html5QrcodeSupportedFormats.UPC_A,
626 Html5QrcodeSupportedFormats.UPC_E,
627 Html5QrcodeSupportedFormats.UPC_EAN_EXTENSION,
628];
629const html5QrcodeScanner = new Html5QrcodeScanner(
630 "reader",
631 { fps: 10, qrbox: 250, formatsToSupport: formatsToSupport },
632 /* verbose= */ false);
633html5QrcodeScanner.render(onScanSuccess);
634```
635
636## How to modify and build
6371. Code changes should only be made to [/src](./src) only.
638
6392. Run `npm install` to install all dependencies.
640
6413. Run `npm run-script build` to build javascript output. The output javascript distribution is built to [/dist/html5-qrcode.min.js](./dist/html5-qrcode.min.js). If you are developing on Windows OS, run `npm run-script build-windows`.
642
6434. Testing
644 - Run `npm test`
645 - Run the tests before sending a pull request, all tests should run.
646 - Please add tests for new behaviors sent in PR.
647
6485. Send a pull request
649 - Include code changes only to `./src`. **Do not change `./dist` manually.**
650 - In the pull request add a comment like
651 ```
652 @all-contributors please add @mebjas for this new feature or tests
653 ```
654 For calling out your contributions - the bot will update the contributions file.
655 - Code will be built & published by the author in batches.
656
657## Credits
658The decoder used for the QRcode reading is from `Zxing-js` https://github.com/zxing-js/library<br>