Giter VIP home page Giter VIP logo

qr-scanner's Introduction

QR Scanner

Javascript QR Code Scanner based on Cosmo Wolfe's javascript port of Google's ZXing library.

In this library, several improvements have been applied over the original port:

  • Web cam scanning support out of the box
  • Uses the browser's native BarcodeDetector if available
  • Lightweight: ~59.3 kB (~16.3 kB gzipped) minified with Google's closure compiler. If the native BarcodeDetector is available, only ~15.3 kB (~5.6 kB gzipped) are loaded.
  • Improved performance and reduced memory footprint.
  • Runs in a WebWorker which keeps the main / UI thread responsive.
  • Can be configured for better performance on colored QR codes.

According to our benchmarking this project's scanner engine's detection rate is about 2-3 times (and up to 8 times) as high as the one of the most popular javascript QR scanner library LazarSoft/jsqrcode. Also the other library oftentimes misreads the content of QR codes, while for this project no misreads occurred in the benchmarking.

The library supports scanning a continuous video stream from a web cam as well as scanning of single images.

The development of this library is sponsored by nimiq, world's first browser based blockchain.

nimiq.com

Demo

See https://nimiq.github.io/qr-scanner/demo/

Installation

To install via npm:

npm install --save qr-scanner

To install via yarn:

yarn add qr-scanner

Or simply copy qr-scanner.min.js and qr-scanner-worker.min.js to your project.

Setup

The QR Scanner consists of two main files. qr-scanner.min.js is the main API file which loads the worker script qr-scanner-worker.min.js via a dynamic import, only if needed. If you are not using a bundler like Rollup or Webpack that handles dynamic imports automatically, you might have to copy qr-scanner-worker.min.js over to your dist, next to qr-scanner.min.js or next to the script into which you're bundling qr-scanner.min.js.

qr-scanner.min.js is an es6 module and can be imported as follows:

import QrScanner from 'path/to/qr-scanner.min.js'; // if using plain es6 import
import QrScanner from 'qr-scanner'; // if installed via package and bundling with a module bundler like webpack or rollup

This requires the importing script to also be an es6 module or a module script tag, e.g.:

<script type="module">
    import QrScanner from 'path/to/qr-scanner.min.js';
    // do something with QrScanner
</script>

If your project is not based on es6 modules you can

import('path/to/qr-scanner.min.js').then((module) => {
    const QrScanner = module.default;
    // do something with QrScanner
});
  • use the UMD build qr-scanner.umd.min.js for direct usage as non-module script
<script src="path/to/qr-scanner.umd.min.js"></script>
<script>
    // do something with QrScanner
</script>
  • bundle qr-scanner.umd.min.js directly with your non-module code with tools like gulp or grunt.
  • bundle the lib with require based bundlers like browserify:
const QrScanner = require('qr-scanner'); // if installed via package
const QrScanner = require('path/to/qr-scanner.umd.min.js'); // if not installed via package
// do something with QrScanner

This library uses ECMAScript 2017 features like async functions. If you need to support old browsers, you can use qr-scanner.legacy.min.js, which is ECMAScript 2015 (ES6) compatible. It's a UMD build and can be used as a replacement for qr-scanner.umd.min.js, see above. Note, that the legacy build is larger as it includes some polyfills and, to support browsers that don't support dynamic imports, inlines the worker script which however would be needed to be loaded in legacy browsers anyway. You will likely not need to use the legacy build though, as general browser support is already very good for the regular build. Especially if you want to scan from the device's camera, camera support by the browser is the stricter restriction.

Usage

Web Cam Scanning

1. Create HTML

Create a <video> element where the web cam video stream should get rendered:

<video></video>

2. Create a QrScanner Instance

// To enforce the use of the new api with detailed scan results, call the constructor with an options object, see below.
const qrScanner = new QrScanner(
    videoElem,
    result => console.log('decoded qr code:', result),
    { /* your options or returnDetailedScanResult: true if you're not specifying any other options */ },
);

// For backwards compatibility, omitting the options object will currently use the old api, returning scan results as
// simple strings. This old api will be removed in the next major release, by which point the options object is then
// also not required anymore to enable the new api.
const qrScanner = new QrScanner(
    videoElem,
    result => console.log('decoded qr code:', result),
    // No options provided. This will use the old api and is deprecated in the current version until next major version.
);

As an optional third parameter an options object can be provided. Supported options are:

Option Description
onDecodeError Handler to be invoked on decoding errors. The default is QrScanner._onDecodeError.
preferredCamera Preference for the camera to be used. The preference can be either a device id as returned by listCameras or a facing mode specified as 'environment' or 'user'. The default is 'environment'. Note that there is no guarantee that the preference can actually be fulfilled.
maxScansPerSecond This option can be used to throttle the scans for less battery consumption. The default is 25. If supported by the browser, the scan rate is never higher than the camera's frame rate to avoid unnecessary duplicate scans on the same frame.
calculateScanRegion A method that determines a region to which scanning should be restricted as a performance improvement. This region can optionally also be scaled down before performing the scan as an additional performance improvement. The region is specified as x, y, width and height; the dimensions for the downscaled region as downScaledWidth and downScaledHeight. Note that the aspect ratio between width and height and downScaledWidth and downScaledHeight should remain the same. By default, the scan region is restricted to a centered square of two thirds of the video width or height, whichever is smaller, and scaled down to a 400x400 square.
highlightScanRegion Set this option to true for rendering an outline around the scan region on the video stream. This uses an absolutely positioned div that covers the scan region. This div can either be supplied as option overlay, see below, or automatically created and then accessed via qrScanner.$overlay. It can be freely styled via CSS, e.g. by setting an outline, border, background color, etc. See the demo for examples.
highlightCodeOutline Set this option to true for rendering an outline around detected QR codes. This uses an absolutely positioned div on which an SVG for rendering the outline will be placed. This div can either be supplied as option overlay, see below, or be accessed via qrScanner.$overlay. The SVG can be freely styled via CSS, e.g. by setting the fill color, stroke color, stroke width, etc. See the demo for examples. For more special needs, you can also use the cornerPoints directly, see below, for rendering an outline or the points yourself.
overlay A custom div that can be supplied for use for highlightScanRegion and highlightCodeOutline. The div should be a sibling of videoElem in the DOM. If this option is supplied, the default styles for highlightCodeOutline are not applied as the expectation is that the element already has some custom style applied to it.
returnDetailedScanResult Enforce reporting detailed scan results, see below.

To use the default value for an option, omit it or supply undefined.

Results passed to the callback depend on whether an options object was provided:

  • If no options object was provided, the result is a string with the read QR code's content. The simple string return type is for backwards compatibility, is now deprecated and will be removed in the future.
  • If an options object was provided the result is an object with properties data which is the read QR code's string content and cornerPoints which are the corner points of the read QR code's outline on the camera stream.

To avoid usage of the deprecated api if you're not supplying any other options, you can supply { returnDetailedScanResult: true } to enable the new api and get the detailed scan result.

3. Start scanning

qrScanner.start();

Call it when you're ready to scan, for example on a button click or directly on page load. It will prompt the user for permission to use a camera. Note: to read from a Web Cam stream, your page must be served via HTTPS.

4. Stop scanning

qrScanner.stop();

If you want, you can stop scanning anytime and resume it by calling start() again.

Single Image Scanning

QrScanner.scanImage(image)
    .then(result => console.log(result))
    .catch(error => console.log(error || 'No QR code found.'));

Supported image sources are: HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, ImageBitmap, OffscreenCanvas, File / Blob, Data URIs, URLs pointing to an image (if they are on the same origin or CORS enabled)

As an optional second parameter an options object can be provided. Supported options are:

Option Description
scanRegion A region defined by x, y, width and height to which the search for a QR code should be restricted. As a performance improvement this region can be scaled down before performing the scan by providing a downScaledWidth and downScaledHeight. Note that the aspect ratio between width and height and downScaledWidth and downScaledHeight should remain the same. By default, the region spans the whole image and is not scaled down.
qrEngine A manually created QR scanner engine instance to be reused. This improves performance if you're scanning a lot of images. An engine can be manually created via QrScanner.createQrEngine(QrScanner.WORKER_PATH). By default, no engine is reused for single image scanning.
canvas A manually created canvas to be reused. This improves performance if you're scanning a lot of images. A canvas can be manually created via a <canvas> tag in your markup or document.createElement('canvas'). By default, no canvas is reused for single image scanning.
disallowCanvasResizing Request a provided canvas for reuse to not be resized, irrespective of the source image or source region dimensions. Note that the canvas and source region should have the same aspect ratio to avoid that the image to scan gets distorted which could make detecting QR codes impossible. By default, the canvas size is adapted to the scan region dimensions or down scaled scan region for single image scanning.
alsoTryWithoutScanRegion Request a second scan on the entire image if a scanRegion was provided and no QR code was found within that region. By default, no second scan is attempted.
returnDetailedScanResult Enforce reporting detailed scan results, see below.

To use the default value for an option, omit it or supply undefined.

Returned results depend on whether an options object was provided:

  • If no options object was provided, the result is a string with the read QR code's content. The simple string return type is for backwards compatibility, is now deprecated and will be removed in the future.
  • If an options object was provided the result is an object with properties data which is the read QR code's string content and cornerPoints which are the corner points of the read QR code's outline on the camera stream.

To avoid usage of the deprecated api if you're not supplying any other options, you can supply { returnDetailedScanResult: true } to enable the new api and get the detailed scan result.

If no QR code could be read, scanImage throws.

Checking for Camera availability

This library provides a utility method for checking whether the device has a camera. This can be useful for determining whether to offer the QR web cam scanning functionality to a user.

QrScanner.hasCamera(); // async

Getting the list of available Cameras

This library provides a utility method for getting a list of the device's cameras, defined via their id and label. This can be useful for letting a user choose a specific camera to use.

You can optionally request the camera's labels. Note that this however requires the user's permission to access the cameras, which he will be asked for if not granted already. If not specifically requested, device labels are determined on a best effort basis, i.e. actual labels are returned if permissions were already granted and fallback labels otherwise. If you want to request camera labels, it's recommendable to call listCameras after a QrScanner instance was successfully started, as by then the user will already have given his permission.

QrScanner.listCameras(); // async; without requesting camera labels
QrScanner.listCameras(true); // async; requesting camera labels, potentially asking the user for permission

Specifying which camera to use

You can change the preferred camera to be used. The preference can be either a device id as returned by listCameras or a facing mode specified as 'environment' or 'user'. Note that there is no guarantee that the preference can actually be fulfilled.

qrScanner.setCamera(facingModeOrDeviceId); // async

Color Inverted Mode

The scanner by default scans for dark QR codes on a bright background. You can change this behavior to scan for bright QR codes on dark background or for both at the same time:

qrScanner.setInversionMode(inversionMode);

Where inversionMode can be original, invert or both. The default for web cam scanning is original and for single image scanning both.

Color Correction

Change the weights for red, green and blue in the grayscale computation to improve contrast for QR codes of a specific color:

qrScanner.setGrayscaleWeights(red, green, blue, useIntegerApproximation = true);

Where red, green and blue should sum up to 256 if useIntegerApproximation === true and 1 otherwise. By default, these values are used.

Flashlight support

On supported browsers, you can check whether the currently used camera has a flash and turn it on or off. Note that hasFlash should be called after the scanner was successfully started to avoid the need to open a temporary camera stream just to query whether it has flash support, potentially asking the user for camera access.

qrScanner.hasFlash(); // check whether the browser and used camera support turning the flash on; async.
qrScanner.isFlashOn(); // check whether the flash is on
qrScanner.turnFlashOn(); // turn the flash on if supported; async
qrScanner.turnFlashOff(); // turn the flash off if supported; async
qrScanner.toggleFlash(); // toggle the flash if supported; async.

Clean Up

You can destroy the QR scanner if you don't need it anymore:

qrScanner.destroy();
qrScanner = null;

This will stop the camera stream and web worker and cleans up event listeners. The QR scanner will be dysfunctional after it has been destroyed.

Build the project

The project is prebuild in qr-scanner.min.js in combination with qr-scanner-worker.min.js. Building yourself is only necessary if you want to change the code in the /src folder. NodeJs is required for building.

Install required build packages:

yarn

Building:

yarn build

qr-scanner's People

Contributors

crisfole avatar curdbecker avatar danimoh avatar filipchalupa avatar lafriks avatar legoscia avatar my6uot9 avatar reustle avatar robinlinus avatar shrpne avatar sisou avatar theapplefreak avatar urakozz avatar wesbos 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

qr-scanner's Issues

"QR Code not found" if image size is to big (2MB)?

I have testet the function "Scan form file:" in demo https://nimiq.github.io/qr-scanner/demo/ with the same image in two different sizes (61 KB, 1500 kb) on a iPhone and WIN10-PC.

With the size 61 KB (and 360kb as well): QR Code was proberly detected
With the size 1500 KB: QR Code was not detectet. "Detected QR code: QR code not found."

Question: Is there a size limit to the Image/file?
How can get around that Problem?

Any help would be great!
Thomas
Attachment: the 2 files/Images
IMG_4417-61KB
IMG_4417-2000KB

help please

Hi,
I'm currently searching for a way to include a qr-scanning plugin in my webapp project. I need access to the mobile phone's camera and the output should be the string / url of the qr-code.
I found your project and tried to include it like described before. However, I get the following error message:

Uncaught DOMException: Failed to construct 'Worker': Script at 'https://nimiq.github.io/qr-scanner/qr-scanner-worker.min.js' cannot be accessed from origin '// my page reference //'.
at new QrScanner (https://nimiq.github.io/qr-scanner/qr-scanner.min.js:2:334)
at // my page reference

Interestingly, I only get the value true or false for the camera existence when referring to your repository but not when referring to my javascripts folder.

Our current architecture is:

  • project_folder
    --> index.html
  • javascripts
    --> qr-scanner.min.js
    --> qr-scanner-worker.min.js

Did I miss something by chance? I would be really grateful for some replies. Thank you very much and have a nice day!

Does not work in Safari on IPhone

There is strage issue in Safari 11+ on IPhones.
There are no errors in browser's console but QR scan is not performed.
Could someone help with this?
Could someone resolve this issue in further app release?

On android everything seems to work fine.

Not working only on iPhone

I have this error only with iPhone :
"NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission."

But I accept that camera can be used.
It's very strange because on iPad it's work perfectly.

Stop scanning for a while

Hi,

How to stop the scanning process until I request it to come back again.

I destroyed the object then recreate it, but it never works.

Is there anyway to do it?

memory leak when trying build in a lit-htm project

When I try and build my project with the WORKER_PATH I get allocation failure GC in old space requested error and the build fails. If I comment out the WORKER_PATH the code compiles without any errors.

The apps appears to run, although I need to serve via SSL, so hence the need to do a build.

I'm using the polymer project's lit-element and doing a polymer build --auto-base-path && gulp prpl-server

The line in my code is:

firstUpdated() {
    QrScanner.WORKER_PATH =  '../components/qr-scanner/qr-scanner-worker.min.js';
    const videoElem = this.shadowRoot.getElementById('scanner') 
    const qrScanner = new QrScanner(videoElem, result => console.log('decoded qr code:', result)); 		
  }

How can i make the reader full width ?

Hi there,

I am using this scanner script to scan the QR code on mobile devices through the browser. But the problem is the reader is not 100% full width or how I can change the scanning angle of the screen?

small qr codes

I was playing around with small (1-2 cm x side) qr codes, and it is very difficult to get a reading. I also added a zoom bar to zoom with camera using "mediaStreamTrack.applyConstraints()", but reading did not improve, even if the QR code was finely focused and covered half of the stream window. Do you have any suggestions on how to improve performance in these cases? I can do some tests.

Scanner error: timeout

I keep getting Scanner error: timeout


(anonymous) | @ | index.js:3714
-- | -- | --
  | (anonymous) | @ | qr-scanner.js:217
  | Promise.then (async) |   |  
  | (anonymous) | @ | qr-scanner.js:214
  | sentryWrapped | @ | index.js:3212
  | requestAnimationFrame (async) |   |  
  | (anonymous) | @ | index.js:3457
  | _scanFrame | @ | qr-scanner.js:213
  | _onPlay | @ | qr-scanner.js:191
  | (anonymous) | @ | 6LBW8-H9LPR-9M23M-JHQ3F-U5FUY:16
  | sentryWrapped | @ | index.js:3212
  | play (async) |   |  
  | _onCanPlay | @ | qr-scanner.js:186
  | (anonymous) | @ | 6LBW8-H9LPR-9M23M-JHQ3F-U5FUY:16
  | sentryWrapped | @ | index.js:3212


There's no additional info. Can someone help me?

camera

Beautiful work. How to manually set to Front Camera?

Flash Light support

Hi. Is this library offer flash light on /off support? Did You considered adding it?

Detecting multiple QR codes

I'm trying to use the library to detect multiple QR codes in a webcam stream. I realized during testing that it does not work. Also the library also does not return the location of a detected code, so I wouldn't be able to distinguish between multiple detected codes anyway.

What I'm thinking now is letting the user give a hint by touching the desired code in the video, so the QR scanner could limit its detection area to the area around the "touch". Is there any way to limit the detection area? Or would I have to do this myself, by using the library in single image mode, and getting a video frame and cropping it around the touch point?

SetTimeout not working when a QR is found

Hi there,
I'm trying to find a solution for this but can't find where the problem is originated in the qr-scanner.js file.

When a QR code is found, the resulting function is being executed multiple times.
You can test it by just changing the demo's function as follow (I'm just adding an alert call)

function setResult(label, result) { alert('setResult'); label.textContent = result; label.style.color = 'teal'; clearTimeout(label.highlightTimeout); label.highlightTimeout = setTimeout(() => label.style.color = 'inherit', 100); }

And you'll see that the alert is executed multiple times.

Can't seem to get this working in Angular

Hi there. I'm keen to give this a try but I can't seem to get this working in Angular. Following the instructions I'm simply placing the two javascript files in a folder in Angular, then importing the first one in a component using the statement provided. For some reason I keep getting a 404 error on finding the worker file. I tried with the min versions first and am now trying with the non-min versions. Here's the code...
`import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import QrScanner from 'src/assets/qr-scanner.js';

@component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
@ViewChild('videoelement') videoelement: ElementRef;
ngOnInit() {
this.showVideo();
}

showVideo() {
const qrScanner = new QrScanner(this.videoelement.nativeElement, result =>
console.log('decoded qr code:', result)
);
}
}`

Here's the change I made in the qr-scanner.js file...
QrScanner.WORKER_PATH = 'worker.js';

I've played with different paths but can't seem to get it to work. I'm sure I'm doing something wrong but any advice would be helpful.

Doesn't Detect QR Code

I've used the exact clone of the repository in my ASP.NET project and it fails to recognize any QR Codes. I also uploaded to an IIS server to see if it was an issue with debugging in Visual Studio, but it still doesn't recognize QR Codes. The demo however, works on all of my devices, so I do not understand why an exact clone would not work.

Scanner error: timeout once using webpack

I'm using webpack on my Project and getting this error once I embed the QR Scanner:

Scanner error: timeout
(anonymous) @ app.708859c27050a514213f.js:113
Promise.then (async)
(anonymous) @ app.708859c27050a514213f.js:113
requestAnimationFrame (async)
_scanFrame @ app.708859c27050a514213f.js:113
_onPlay @ app.708859c27050a514213f.js:113
play (async)
_onCanPlay @ app.708859c27050a514213f.js:113

Hier is the Code that I'm using:

import QrScanner from 'qr-scanner';
import QrScannerWorkerPath from '!!file-loader!../../../node_modules/qr-scanner/qr-scanner-worker.min.js';

export default () => {
    const video = document.getElementById('qr-video');
    const camHasCamera = document.getElementById('cam-has-camera');
    const camQrResult = document.getElementById('cam-qr-result');
    const camQrResultTimestamp = document.getElementById('cam-qr-result-timestamp');

    function setResult(label, result) {
        label.textContent = result;
        camQrResultTimestamp.textContent = new Date().toString();
        label.style.color = 'teal';
        clearTimeout(label.highlightTimeout);
        label.highlightTimeout = setTimeout(() => label.style.color = 'inherit', 100);
    }

        QrScanner.WORKER_PATH = QrScannerWorkerPath;

        QrScanner.hasCamera().then(hasCamera => camHasCamera.textContent = hasCamera);

        const scanner = new QrScanner(video, result => setResult(camQrResult, result));
        scanner.start();
};

Any help is highly appreciated.

Does not work in desktop

Hello
I have problem in desktop
I can work with this in mobile but on my laptop does not work with firefox or chrome
Demo either does not work!!
Can you help me please

Cannot decode image

When I upload the original QR Code image file, it cannot be decoded, however if I take the qr code image with camera and upload, it work. Wonder why?

Image that not work
qr-code

Image that work:
20180719_093137 copy
20180719_093137
20180720_180930 copy

Uncaught SyntaxError: Unexpected token export

Keep getting Uncaught SyntaxError: Unexpected token export error. Any idea how to resolve this? Thx
Edit: in safari the error is slightly different:
[Error] SyntaxError: Unexpected keyword 'export' (anonymous function) (qr-scanner.min.js:3)

Edit2:
I am not using node.js on this project - is it necessary?

Camera is only enable if you are in https

I will play this plugin in my localhost but i received that 'The camera stream is only accessible if the page is transferred via https'

Should localhost be start normally?

utf-8 encode

How can we read utf-8 encoded text?
it doesn't show correctly on my text and my meta on the page have charset="UTF-8"

Data matrix

is it possible to add support for data matrix?

iOS Chrome

The Qr Scanner does not work in ios google chrome. Does anyone know how to solve it?
I've already put the muted and playsinline in the video tag. It works perfect in android chrome and ios safari. Also I've already use https

Refused to execute script - because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

I'm using Angular 7, works fine on localhost but in production i see the error below. Any ideas how to get around it?

Refused to execute script from '<domain>/assets/qr-scanner-worker.min.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

After some digging around i came across this statement but still more idea:

When you have a script that is not in the head of a document, the javascript it loads is labeled with the wrong mime type ('text/html')

is there an npm package?

couldn't find anything on the readme about using this in a project other than just... downloading the files myself

Need to export QrScanner properly and need to call .start()

Just a suggestion, but you may wish to include something like.
When ready to open the QR scanner, be sure to call

QrScanner.start();

I had to follow the code to find that. It might be obvious to you, but technically it's undocumented.
Also the minified version isn't exporting QrScanner. It exports "e". You should check whatever you've got munging your build and ensure it preserves the class name.

Other than that, Great work!

Can not detect qr code

Hello, I found this image can not be detected correctly.

data:image/png;base64,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

This image is generated by phpmyadmin for totp authentication.

I write a demo here https://codesandbox.io/s/x999ll650w .

SyntaxError: Unexpected token export

I've just installed lib via npm install --save qr-scanner and declared it const QrScanner = require('qr-scanner')

And I`m getting this error:

/home/khuzha/myprojects/bots/oneqrbot/node_modules/qr-scanner/qr-scanner.min.js:11
else{let d,f;d=()=>{a.removeEventListener("load",d);a.removeEventListener("error",f);c()};f=()=>{a.removeEventListener("load",d);a.removeEventListener("error",f);b("Image load error")};a.addEventListener("load",d);a.addEventListener("error",f)}})}}e.DEFAULT_CANVAS_SIZE=400;e.WORKER_PATH="qr-scanner-worker.min.js";export default e;
                                                                                                                                                                                                                                                                                                                           ^^^^^^

SyntaxError: Unexpected token export
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:616:28)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/khuzha/myprojects/bots/oneqrbot/bot.js:2:19)

How can i use this scripts in php file ?

Hi there,

My project is in PHP language and I need a QR code scanner by enabling the webcam or mobile camera.

I have used your scripts and created a new object using the following code in .php file

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script type="text/javascript" src="<?php echo get_site_url(); ?>/wp-content/themes/north-shore-child/qr-scanner.min.js"></script>
	<script type="text/javascript" src="<?php echo get_site_url(); ?>/wp-content/themes/north-shore-child/qr-scanner-worker.min.js"></script>
</head>
<body>
	<video></video>

	<script type="text/javascript">
		const qrScanner = new QrScanner(videoElem, result => console.log('decoded qr code:', result));
	</script>
</body>
</html>

But it throws an error :

Screenshot 2019-07-06 at 1 04 47 PM

Can anyone help me here?

How do you unload or stop the worker?

it seems that calling scanner.stop() doesn't also stop the woker.

when I create multiple scanners (such as reading a QR Code, navigating somewhere, and coming back to read a different QR Code), I end up having multiple workers, and the old workers are still running.

image

Selecting the front camera

Thanks for what so far seems like a great library! Is there a way of selecting the front camera for phones and tablets?

Importing main script requires script in non-existing folder

When I import import QrScanner from 'qr-scanner/qr-scanner.min.js';

In one of my modules I get a 404 when that script is imported cause it's trying to import the worker script from a non-existent libraries folder.

https://webapp.localhost/libraries/qr-scanner/qr-scanner-worker.min.js

It should not have paths hardcoded and should be using bare module imports

Compile library with advanced closure compiler settings

Might save another 10kb.

Special attention will have to be spent on the options object handed over to jsQR and the grayscaleWeigths defaults. While these are used internally only, the way they are merged together might confuse closure compiler.

Also the way typescript compiles enums is not compatible with closure compiler.

Compiling from typescript source with https://github.com/angular/tsickle might be good.

Uncaught (in promise) Camera not found.

Facing issue like this it was showing wrong path for qr-scanner-worker.min.js also faced some other issue solved them but not able to solve this one. If anyone here have solution for this please guide me.

Call QR scanner in a function

Hi danimoh,
first I would like to appreciate your module. I have been trying your qr scanner. I could successfully include your qr scanner and it basically worked fine.
However, at the moment the camera is active the whole time. Precisely, the camera is active immediately after the html-page has been loaded and it remains active even after the qr scanner has successfully detected a qr-code. This is the only possibility at the moment for me to make the qr-scanner work.

In your usage description, I found code for starting and destroying the qr scanner instance.
Therefore, I tried to include the code scanner.start() in one of my functions.
These functions are only used after the user has fired an event through user input.
My javascript functions are loaded from a seperated file by the tag

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

The qr-script however is embedded in a <script type="module"></script> tag.
I assume that the different attribute of the script-tags is the problem.

Is there any possibility to use the scanner.start() function in my own functions?
Where can I use the scanner.destroy() function?

I would be grateful if you have a solution for my problem.

Kind Regards
WeiYWei

update webpack readme setup + missing usage code

in setup it says to use

import QrScannerWorkerPath from '!!file-loader!./node_modules/qr-scanner/qr-scanner-worker.min.js';

but it's not working for me ... it works only when:

import QrScannerWorker from '!!file-loader!qr-scanner/qr-scanner-worker.min.js';

in Usage, there should be included this code:

qrScanner.start();

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.