GithubHelp home page GithubHelp logo

yudielcurbelo / react-qr-scanner Goto Github PK

View Code? Open in Web Editor NEW
181.0 181.0 21.0 57.69 MB

A library to scan QR Codes in react.

Home Page: https://yudielcurbelo.github.io/react-qr-scanner/

License: MIT License

JavaScript 2.19% TypeScript 97.81%
qr qr-code qrcode-reader qrcode-scanner react reactjs reader scanner typescript

react-qr-scanner's People

Contributors

considerate avatar idindrakusuma avatar raghupviyer avatar yudielcurbelo 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

react-qr-scanner's Issues

Camera loading in ionic react-app

when I try to use the scanner in an ionic react app for my android phone, the app runs fine on my laptop webapp and the camera opens, but whenever I build in android studio and try to launch the app on my android device it just shows a big triangle play icon and the word loading
Screenshot_20240521-105851_camera-scanner

Audio is not defined

When I npm run build

ReferenceError: Audio is not defined

version: ^2.0.0-beta.3

How can I solve it?

Request for Documentation: Details on Errors

Thank you for creating and maintaining this project โœจ
It would be helpful if there were a document detailing what kinds of errors are handled by the onError function, so that I can translate the error messages for each individual case.

I found this file, but it doesn't appear to be used in the component.
src/misc/index.ts

Allow versions < React 18 as peer dependency

Hi! ๐Ÿ‘‹

Firstly, thanks for your work on this project! ๐Ÿ™‚

Today I used patch-package to patch @yudiel/[email protected] for the project I'm working on.

I am using this package in scope of a react 17 based project. From what I saw across the repo, the package does not actively use any React 18 features.

Couldn't we open the peer dependency version range to allow other versions than react 18?

Here is the diff that solved my problem:

diff --git a/node_modules/@yudiel/react-qr-scanner/package.json b/node_modules/@yudiel/react-qr-scanner/package.json
index c2c824d..f897269 100644
--- a/node_modules/@yudiel/react-qr-scanner/package.json
+++ b/node_modules/@yudiel/react-qr-scanner/package.json
@@ -55,7 +55,7 @@
     "typescript": "^5.4.5"
   },
   "peerDependencies": {
-    "react": "^18.2.0",
+    "react": "^17.0.0 || ^18.2.0",
     "react-dom": "^18.2.0"
   },
   "dependencies": {

This issue body was partially generated by patch-package.

Scanner doesn't recognize colored qr codes

I have custom QR codes that are different colors, the scanner is not able to pick up any colors (apart from background::white foreground::black)

Any workaround for this issue?

Is custom viewfinder available?

hi, I update to lastest version and found the custom viewfinder is gone. Is there any way to custom it in new version or can i disable it?

How to close the QrScanner properly once we got the result ?

I create a dialog component and put QrScanner in dialog content, when I get the result I would like to close the dialog also close the camera as well, but I got error when dialog is closing.

I'm a newbie in React your help is much appreciated

Error message:

Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The source width is 0.

My source code

import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Typography,
} from "@mui/material";
import { QrScanner } from "@yudiel/react-qr-scanner";

function Scanner({ open, setOpen, onDecode }) {
const handleClose = () => {
setTimeout(() => setOpen(false), 0);
};

return (


Scan Package by camera

<DialogContent
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<QrScanner
onDecode={(result) => {
if (result) {
onDecode(result);
setOpen(false);
}
}}
onError={(err) => {
console.error(err?.message);
}}
/>


<Button
variant="outlined"
color="secondary"
sx={{ px: 5 }}
onClick={handleClose}
>
Close



);
}

export default Scanner;

"Could not start video source" error on Android 7 and Chrome 109

Hey, first of all, thank you for this lib, it's awesome.
Unfornutelly I found one glitch. When I run Storybook demo on the Android 7 and Chrome 109.0.5414 video is not starting. Instead, I see the "Could not start video source" error.
Seems like this is called for some reason.

image

I have the same issue in my react app using your library. On Android 8 it works well.
This Android device can run camera video (check other websites to test if it's device related issue).

Is there a chance to look at it from your side? Thank you in advance!

New version implementation

Hi, so I have been using the 2.0.0 beta 3 version, with ionic to deploy on mobile. Recently I see that there has been some newer update and I am looking to integrate the new version of the scanner. Can you give me some pointer? as to how I can adapt the code to the new version, since I see that the onScan return is different now. Thank you

import { SetStateAction, useState } from "react";
import { Scanner } from "@yudiel/react-qr-scanner";

export default function App() {
  const [data, setData] = useState("no result");
  const [stopDecoding, setStopDecoding] = useState(true);
  const [startTime, setStartTime] = useState<any>(null);
  const [elapsedTime, setElapsedTime] = useState<any>(null);

  const handleClick = () => {
    setStopDecoding((stop) => !stop);
    if (stopDecoding) {
      setStartTime(Date.now()); // Record the start time
      setElapsedTime(null); // Reset the elapsed time
    }
  };

  const handleError = (error: { message: string | string[]; }) => {
    console.error("Scanner error:", error);
    if (error.message.includes("play() request was interrupted")) {
      console.log("Retrying video play...");
    }
  };

  const handleResult = (text: SetStateAction<string>, result: any) => {
    setData(text);
    setStopDecoding(true);
    const endTime = Date.now();
    setElapsedTime(endTime - startTime); // Calculate the elapsed time
  };

  return (
    <div className="App">
      <p>{data}</p>
      {elapsedTime !== null && <p>Scan Time: {elapsedTime} ms</p>}
      <button onClick={handleClick}>SCAN TRACK</button>
      {!stopDecoding && (
        <Scanner
          onResult={handleResult}
          enabled={!stopDecoding}
          onError={handleError}
        />
      )}
    </div>
  );
}

QR code not scanning

I have set this up in a little app and while most QR codes seem to work no problems, this one in the image and a few others don't seem to work.
I get no errors, it's like it just doesn't recognise it as a QR code.

However, using an iPhone camera I get a URL to google drive from it for a restaurant menu, so it seems to be a valid QR code.
Do you have any ideas why it wouldn't work?

image

Select back camera

Is it possible to select, which back camera should device use? In nowadays, a lot of mobile devices has more than one back camera, on Android this QR scanner selected my zoom camera, which has worst quality, instead of main back camera. I tested it in 2 devices, with the same result.

When I'm trying to fill in "deviceId" field with proper it, then it doesn't work.

How to use the useContinuousScanner

I mainly want to create a custom scanner since most of your components are not customizable but with the same functionality as it has. I found this hook but I do not understand how to use it. Any example would help immensely.

Lack of customisation for individual elements

Add customisation prop to add in custom components for various elements. Most notably "Loading..." text to add matching loading icons/spinners/text as rest of site.

Can be extended to make it easier for other customisations not easy/possible with the CSS markers.

Flip the camera preview image when needed

It would be great if the video element with the camera preview shows the image 'flipped' if the camera is facing the user. That way left&right make more sense, e.g. when on a laptop and you're holding up a QR code you can easier put it inside the view.

From my quick research:

  • On desktop (laptop) browsers every camera can point somewhere else, but I suppose it's safe to assume it faces the user. I think it does not return a facingMode in stream.getVideoTracks[0].getCapabilities().
  • On mobile browser it seems you can get the facingMode from stream.getVideoTracks[0].getCapabilities().

So perhaps the video preview should be flipped always, unless stream.getVideoTracks[0].getCapabilities().facingMode === 'environment' ?

A video can be flipped by applying this style: { transform: scaleX(-1); }.

I can create a PR for this, but maybe you have certain reasons to not implement it?

Feature request - Pause reading

Thanks for your library, I'm trying to implement application to verify vouchers and it fits perfectly. But I'm missing one feature - pause reading.

Imagine scenario:

  1. Person at the entrance reads QR code and I send request to server. - Here I would perform pause reading
  2. Waiting for server response about validity and details. - show details.
  3. Show popup for lets say 5 seconds with details.
  4. Unpause reading

I can do videoElement.pause() but which freeze the video. But then your app is constantly performing reading on that element. I know I can increase the scanDelay. But I would like to freeze it until timeout is gone or some click happen etc. And have possibility to pause reading instead of playing with scanDelay would be easier.

I want to perform pause to not send more request to server.

Thanks

Failed to parse source map from warnings

Thanks for building and maintaining this library.
I'm getting source map warnings when running react-scripts start (CRA).

react version: 18.2.0
react-qr-scanner version: 1.1.4

Failed to parse source map from '/usr/src/app/node_modules/@yudiel/src/components/Counter.tsx' file: Error: ENOENT: no such file or directory, open '/usr/src/app/node_modules/@yudiel/src/components/Counter.tsx'

Failed to parse source map from '/usr/src/app/node_modules/@yudiel/src/components/Finder.tsx' file: Error: ENOENT: no such file or directory, open '/usr/src/app/node_modules/@yudiel/src/components/Finder.tsx'

Failed to parse source map from '/usr/src/app/node_modules/@yudiel/src/components/QrScanner.tsx' file: Error: ENOENT: no such file or directory, open '/usr/src/app/node_modules/@yudiel/src/components/QrScanner.tsx'

...

Audio is not defined.

So, i am trying to run the package on a next JS app, and i get this error, some on know how to fix?

Captura de Tela 2024-02-20 aฬ€s 22 14 57

Camera Stream Continues After Modal Closure Due to Premature Unmount

Description

When using the scanner component inside a modal, if the modal is closed before the camera feed has fully initialized, the camera continues to run in the background. This issue seems to stem from a race condition where the clean-up function executes before the camera has been fully set up, leading to the stream not being properly stopped.

Steps to reproduce

  1. Open the modal which initializes the scanner component to start the camera stream.
  2. Close the modal quickly before the camera feed fully initializes.
  3. Notice that the camera light (if available on the device) remains on, indicating that the stream has not been stopped.

Expected behavior

Closing the modal should also stop the camera stream completely, regardless of whether the camera has fully initialized or not.

Actual behavior

The camera remains on even after the modal has been closed if the modal is closed before the camera feed is completely initialized.

Update README Documentation

Please update the README doc to reflect the import changes.

import {QrScanner} from '@yudiel/react-qr-scanner

to

import { Scanner } from '@yudiel/react-qr-scanner';

2.0b3 continuous scanning even when using with default settings

Hi
I recently did a yarn upgrade-interactive and for some unknown reason I got the 2.0 version proposed. Anyway, when running it via the following (what I consider to be the default component integration):

  <Scanner
            onResult={onQrCodeReceived}
            onError={error => console.log('scan error', error?.message)}
          />

I do get continuous scanning even though I no longer show a QR code to the camera (so I hear a loud beep every 1s or so).

it's not possible to set some of the constraints

I encountered an issue with certain Samsung devices (e.g. S22) where the camera fails to focus properly, resulting in blurry QR codes that cannot be scanned. Upon researching potential solutions on the internet, it appears that setting the auto-focus constraint focusMode: continuous may resolve the issue. Here's an example of how I try to use the constraints:

constraints={{
  facingMode: 'environment',
  focusMode: 'continuous',
}}

However, when attempting to set the focusMode property, I encountered the following error:

Type '{ facingMode: string; focusMode: string; }' is not assignable to type 'MediaTrackConstraints'.
  Object literal may only specify known properties, and 'focusMode' does not exist in type 'MediaTrackConstraints'.

Upon inspecting the library source code, I observed that the constraints prop is passed to the Finder component and utilized in the useMediaDevices hook, as seen here: useMediaDevices.ts.

Additionally, I noticed that there is an open issue (#22) on the repository regarding similar zoom constraint problem.

It seems logical to me that it should be possible to pass constraints such as focusMode or zoom to window.navigator.mediaDevices, especially when browser console output from navigator.mediaDevices.getSupportedConstraints() clearly states that those constraints do exist in the browser API.

Sources:
https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints#focusmode

https://forum.developer.samsung.com/t/camera-auto-focus-and-zoom-camera-not-working-in-the-web-application/27908/1

mebjas/html5-qrcode#308

Besides that, it is a great library and works flawlessly on apple devices without any problems.

Kindly requesting @yudielcurbelo for any assistance or suggestions on how to address these issues.

Getting warnings while starting/building the project

Getting following warnings while starting/building react project.
I am using this version of package : "@yudiel/react-qr-scanner": "^2.0.0-beta.3"

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/assets/CameraOff.tsx' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/assets/CameraOff.tsx'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/assets/CameraOn.tsx' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/assets/CameraOn.tsx'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/assets/TorchOff.tsx' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/assets/TorchOff.tsx'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/assets/TorchOn.tsx' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/assets/TorchOn.tsx'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/assets/base64Beep.ts' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/assets/base64Beep.ts'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/components/OnOff.tsx' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/components/OnOff.tsx'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/components/Scanner.tsx' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/components/Scanner.tsx'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/components/Torch.tsx' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/components/Torch.tsx'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/hooks/useContinuousScanner.ts' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/hooks/useContinuousScanner.ts'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/hooks/useDeviceList.ts' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/hooks/useDeviceList.ts'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/misc/defaultComponents.ts' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/misc/defaultComponents.ts'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/misc/defaultOptions.ts' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/misc/defaultOptions.ts'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/misc/defaultStyles.ts' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/misc/defaultStyles.ts'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/scanners/BrowserMultiFormatScanner.ts' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/scanners/BrowserMultiFormatScanner.ts'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/scanners/BrowserScanner.ts' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/scanners/BrowserScanner.ts'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/scanners/HTMLCanvasElementLuminanceSource.ts' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/scanners/HTMLCanvasElementLuminanceSource.ts'

WARNING in ./node_modules/@yudiel/react-qr-scanner/dist/esm/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/home/node_modules/@yudiel/react-qr-scanner/src/utilities/browser.ts' file: Error: ENOENT: no such file or directory, open '/home/node_modules/@yudiel/react-qr-scanner/src/utilities/browser.ts'

Large chunks when using with Vite

If you get warnings when running vite build:

(!) Some chunks are larger than 500 kBs after minification. Consider:
- Using dynamic import() to code-split the application
- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks
- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.

You can fix it by splitting vendor chunk inside your vite.config.ts file:

import { defineConfig, splitVendorChunkPlugin } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react(), splitVendorChunkPlugin()],
  build: {
    rollupOptions: {
      output: {
        manualChunks(id: string) {
          // creating a chunk to react-qr-scanner deps. Reducing the vendor chunk size.
          if (id.includes('@yudiel/react-qr-scanner'))
            return '@qr-scanner'
        },
      },
    },
  },
})

Bar codes are not getting scanned

Hi @yudielcurbelo ,

I am implementing a feature where we are scanning bar codes on stickers. Bar codes are very small in size, so we might need auto detect bar code feature / zoom feature.

I tried below versions but no luck with scanning. Even below sample is also not working. onScan function itself is not getting triggered for v2.0.0-beta.15
We decided to go with this library by checking demo.

Demo works fine without any issue, Can you please share the code snippet of demo for reference?

Versions - 2.0.0-beta.15, 2.0.0-beta.3, 1.2.10

Below is my code snippet of v2.0.0-beta.15

import { useState } from 'react'
import {Scanner, useDevices, centerText, boundingBox} from '@yudiel/react-qr-scanner';

export const BarcodeScanner = () => {
  const [result, setResult] = useState(null);
  const [pauseScaner, setPauseScaner] = useState(false);
  const devices = useDevices();
  const onScanComplte = (result) => {
    console.log("result--->", result);
    setResult(result?.rawValue);
    setPauseScaner(true);
  }
  return (
    <div>
      <div>Result-{result}</div>
      <div style={{ width: 500, height: 500 }}>
        <video id='videoElement' autoPlay style={{ width: 0, height: 0 }}/>
        <Scanner
          videoId={'videoElement'}
          scanDelay={500}
          paused={pauseScaner}
          torch={true}
          constraints={{
            facingMode: "environment",
            deviceId: devices?.[0]?.deviceId,
          }}
          allowMultiple={true}
          //formats={["CODE_128"]}
          onScan={onScanComplte}
          components={{
            audio: true,
            onOff: true,
            finder: true,
          }}
          onError={(error) => console.log(error?.message)}
        />
      </div>
    </div>
  );
}

Below is code snippet of v2.0.0-beta.3

import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { Scanner, useDeviceList } from "@yudiel/react-qr-scanner";
import Dropdown from '../Common/Dropdown';

export const BarcodeScanner = ({ asset }) => {
	const [scannerFlag, setScannerFlag] = useState(true);
	const  devices  = useDeviceList();
	const videoDeviceOptions = useMemo(() => (
			devices
			.filter((device) => device.kind === 'videoinput')
			.map((device) => ({ value: device.deviceId, label: device.label }))
		), [devices]);
	const [selectedVideoDevice, setSelectedVideoDevice] = useState('');


	const handleScan = useCallback(async (text, result) => {
		console.log('Text, Result-->', text, result);
	}, []);

	useEffect(() => {
		if (devices.length > 0 && !selectedVideoDevice) {
			setSelectedVideoDevice(devices[0]?.deviceId)
		}
	}, [devices, selectedVideoDevice]);

	return (
		<div className="flex w-full min-h-screen items-center flex-col bg-black/80">
			<div className="w-3/4 md:w-1/2 sm:w-3/4 flex justify-center items-center">
				<Dropdown
					className="mt-[2.25rem]"
					name="videoDevice"
					placeholder="Select Device"
					isFormField={false}
					disabled={false}
					options={videoDeviceOptions}
					selectedOption={selectedVideoDevice}
					onChangeValue={setSelectedVideoDevice}
				/>
			</div>
			<div className="w-3/4 lg:w-1/2 md:w-1/2 sm:w-3/4 h-auto">
				<video
					id="videoElement"
					className={`${!scannerFlag && 'hidden'} h-0 w-0`}
				></video>
				<Scanner
					videoId="videoElement"
					enabled={selectedVideoDevice && scannerFlag}
					onResult={handleScan}
					options={{
						constraints: {
							facingMode: 'environment',
						},
						...(selectedVideoDevice ? { deviceId: selectedVideoDevice } : {}),
					}}
					styles={{
						container: {
							backgroundColor: 'rgb(0 0 0 / 0.8)',
						},
					}}
					components={{
						tracker: true,
						audio: true,
						torch: true,
						//count: true,
						onOff: true,
					}}
					onError={(error) => console.log(error?.message)}
				/>
			</div>
		</div>
	);
};

export default Scanner;

Sample Bar code-
barcode

Camera remains on after setting "tracker" to false.

I'm not sure what's happening, but it seems like tracker= doesn't work for me:

const [stopDecoding, setStopDecoding] = useState(false);
... code ....
<QrScanner
            stopDecoding={stopDecoding}
            tracker={false} // tracker={stopDecoding} <-- I tried using false in purpose to see how would this act. Camera remains on.
            onScan={(value) => {
            console.log({ value });
         }}
     onError={handleError}
     aspectRatio="1:1"
/>

Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The source width is 0.

Setup:

  • @yudiel/react-qr-scanner v1.2.4
  • React v18.2.0
  • React Router DOM v6.21.2

I have a simple React app which needs to read a QR code and pass the contents to the backend API for a scoring system.

<QrScanner
  onDecode={code => {
    console.log('Navigate to captured code:', code)
    navigate('/display-code', { state: { code } })        
  }}
  onError={error => {
    console.error(error?.message)
    throw error
  }}
/>

This QR Scanner works fine, except for if I call React Router's navigate (from the useNavigate() hook) it throws the following error:

ERROR
Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The source width is 0.
    at e.makeBufferFromCanvasImageData (http://localhost:3000/static/js/bundle.js:16610:34)
    at new e (http://localhost:3000/static/js/bundle.js:16607:69)
    at t.createBinaryBitmap (http://localhost:3000/static/js/bundle.js:17183:13)
    at t.decode (http://localhost:3000/static/js/bundle.js:17178:20)
    at n (http://localhost:3000/static/js/bundle.js:17170:21)

Googling around, it appear to be a dirty dismount issue.

My workaround is to throw the error away, and it all works fine:

<QrScanner
 onDecode={code => {
   console.log('Navigate to captured code:', code)
   navigate('/display-code', { state: { code } })        
 }}
 onError={error => {
   // We get this error message after capturing a code
   if (error?.message.startsWith("Failed to execute 'getImageData' on 'CanvasRenderingContext2D':")) return 
   // We should report all other errors
   console.error(error?.message)
   throw error
 }}
/>

Is there something missing I should be doing before calling navigate?

Zoom level

It would be great to be able to adjust the zoom level. Is that possible? I am building an app that needs to scan small QR code that can be at a distance as well. Ability to zoom is a necessity it seems.

Scanner is not working in android apps

when I try to use the scanner in android app for my android phone, the app runs fine on my laptop webapp and the camera opens, but whenever I open it in android app I am getting blank screen I have also tried your new version 2.0.0-beta but still not working attaching the screenshot below
Screenshot_20240527-111119_Teams

README document is not up to date

Facts:

  • for this version

"@yudiel/react-qr-scanner": "2.0.0-beta.3"

I get Scanner as bellow

import { Scanner } from '@yudiel/react-qr-scanner';

there is no QrcodeScanner exported

ERROR: Failed to execute 'detect' on BarcodeDetector': Barcode detection service unavailable

When trying to open the camera on a Galaxy TAB A8 tablet and received this error 'ERROR: Failed to execute 'detect' on BarcodeDetector': Barcode detection service unavailable'
, I've already tried to look for solutions for contouring, but without success, I'm only using it to read QRCodes but it says it doesn't have access to barcodes, how do I make it only stay on QRCodes?

Thank you for your attention and I am available if you need me.
ERROR

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.