html5-qrcode vs jsqr vs qr-scanner vs qrcode-reader
Web 端二维码扫描库技术选型与架构对比
html5-qrcodejsqrqr-scannerqrcode-reader类似的npm包:

Web 端二维码扫描库技术选型与架构对比

html5-qrcodejsqrqr-scannerqrcode-reader 都是用于在浏览器环境中识别二维码的 JavaScript 库,但它们的抽象层级和适用场景截然不同。

html5-qrcode 提供了最高层的封装,内置了相机权限管理、视频流处理和 UI 组件,适合快速集成。 qr-scanner 专注于现代浏览器性能,利用 Web Workers 进行解码,API 基于 Promise,适合对性能有要求的项目。 jsqr 是一个底层库,仅处理图像数据解码,不涉及相机或视频流,适合需要完全自定义采集流程的场景。 qrcode-reader 是早期的经典库,目前维护频率较低,通常仅用于维护旧项目,新开发不建议使用。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
html5-qrcode06,1202.63 MB4333 年前Apache-2.0
jsqr04,007-965 年前Apache-2.0
qr-scanner02,862524 kB118-MIT
qrcode-reader0283-179 年前Apache-2.0

Web 端二维码扫描库深度对比:架构、性能与工程实践

在 Web 端实现二维码扫描功能时,开发者常面临选型困难。html5-qrcodejsqrqr-scannerqrcode-reader 代表了四种不同的技术路线。本文将从初始化流程、数据流处理、性能架构及维护状态四个维度进行深度剖析,帮助架构师做出明智决策。

📹 相机与视频流管理:封装层级决定开发效率

处理相机权限和视频流绑定是扫描功能最繁琐的部分。不同库对此的抽象程度差异巨大。

html5-qrcode 提供了最高级的封装,甚至内置了完整的 UI 界面。

  • 自动请求相机权限。
  • 自动绑定视频流到容器。
  • 提供 Html5QrcodeScanner 类,一行代码即可生成带 UI 的扫描器。
// html5-qrcode: 内置 UI 扫描器
import { Html5QrcodeScanner } from 'html5-qrcode';

const scanner = new Html5QrcodeScanner(
  "reader", 
  { fps: 10, qrbox: 250 }
);
scanner.scan((decodedText) => console.log(decodedText));

qr-scanner 提供了中等封装,需要你自己提供视频元素,但自动处理流绑定。

  • 不生成 UI,只处理逻辑。
  • 自动处理相机启动和停止。
  • 适合需要自定义 UI 但不想处理媒体流底层细节的场景。
// qr-scanner: 绑定现有视频元素
import QrScanner from 'qr-scanner';

const video = document.getElementById('video');
const scanner = new QrScanner(video, (result) => console.log(result));
scanner.start();

jsqr 完全不处理相机或视频流。

  • 它只接收图像数据(Uint8ClampedArray)。
  • 开发者必须手动使用 navigator.mediaDevices 获取流并绘制到 Canvas。
  • 适合需要完全控制采集管道的场景。
// jsqr: 需手动获取流并提取数据
const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } });
video.srcObject = stream;
video.play();

// 在 requestAnimationFrame 中提取数据
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR(imageData.data, imageData.width, imageData.height);

qrcode-reader 同样不处理相机,且 API 较为陈旧。

  • 依赖外部图像对象或 Canvas。
  • 回调风格较为老旧,缺乏现代异步支持。
// qrcode-reader: 传统回调风格
import QrcodeReader from 'qrcode-reader';

const reader = new QrcodeReader();
reader.callback = (err, value) => {
  if (err) console.error(err);
  else console.log(value.result);
};
reader.decode(imageElement); // 需要预先准备好的图像元素

🔄 解码回调与数据流:同步阻塞 vs 异步非阻塞

解码过程是计算密集型操作,如何处理解码结果直接影响主线程性能。

html5-qrcode 使用回调函数处理结果。

  • 配置简单,但深层嵌套可能导致代码难以维护。
  • 内部做了节流处理,避免高频回调。
// html5-qrcode: 回调处理
html5QrCode.start(
  { facingMode: "environment" },
  { fps: 10, qrbox: { width: 250, height: 250 } },
  (decodedText, decodedResult) => {
    console.log(`Code matched = ${decodedText}`, decodedResult);
  },
  (errorMessage) => {
    // 处理解析错误(通常每帧都会发生,直到找到码)
  }
);

qr-scanner 支持 Promise 和回调两种模式。

  • 构造函数传入回调,但也提供 scanImage 返回 Promise。
  • 内部使用 Web Worker,解码不在主线程运行。
// qr-scanner: 支持 Promise 的静态扫描
import QrScanner from 'qr-scanner';

try {
  const result = await QrScanner.scanImage(fileInput.files[0]);
  console.log(result);
} catch (error) {
  console.error('No QR code found');
}

jsqr 是纯同步函数。

  • 直接在调用线程执行解码。
  • 如果在主线程高频调用(如每帧),可能导致页面卡顿。
  • 开发者需自行决定是否放入 Web Worker。
// jsqr: 同步解码
const code = jsQR(imageData.data, imageData.width, imageData.height, {
  inversionAttempts: "dontInvert",
});

if (code) {
  console.log(`Found QR code: ${code.data}`);
}

qrcode-reader 也是同步解码,但通过回调返回。

  • 解码过程阻塞调用线程。
  • 错误处理依赖回调的第一个参数。
// qrcode-reader: 同步解码 + 回调
reader.decode(imageElement); 
// 结果通过 reader.callback 异步返回,但解码本身是阻塞的

🖼️ 静态图片扫描:文件上传场景的支持

除了实时摄像头扫描,上传本地图片识别二维码也是常见需求。

html5-qrcode 提供了专门的 scanFile 方法。

  • 自动处理文件读取和解码。
  • API 统一,与摄像头扫描接口风格一致。
// html5-qrcode: 文件扫描
const html5QrCode = new Html5Qrcode("reader");
html5QrCode.scanFile(fileInput.files[0], true)
  .then((decodedText) => console.log(decodedText))
  .catch((err) => console.error(err));

qr-scanner 提供了优化的 scanImage 静态方法。

  • 性能较好,支持多种图片格式。
  • 返回 Promise,易于集成到 async/await 流程。
// qr-scanner: 文件扫描
const result = await QrScanner.scanImage(fileInput.files[0], {
  returnDetailedScanResult: true
});
console.log(result);

jsqr 没有文件扫描方法。

  • 需要开发者手动使用 FileReader 读取文件并绘制到 Canvas。
  • 增加了样板代码,但灵活性最高。
// jsqr: 需手动处理文件读取
const reader = new FileReader();
reader.onload = (e) => {
  const img = new Image();
  img.onload = () => {
    ctx.drawImage(img, 0, 0);
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const code = jsQR(imageData.data, imageData.width, imageData.height);
  };
  img.src = e.target.result;
};
reader.readAsDataURL(fileInput.files[0]);

qrcode-reader 支持图像元素解码。

  • 同样需要手动读取文件为图像对象。
  • 兼容性较好,但流程繁琐。
// qrcode-reader: 需手动处理文件读取
const reader = new FileReader();
reader.onload = (e) => {
  const img = new Image();
  img.onload = () => reader.decode(img);
  img.src = e.target.result;
};
reader.readAsDataURL(fileInput.files[0]);

⚙️ 性能架构与维护状态:工程化决策的关键

在大型应用中,库的维护状态和性能架构决定了长期成本。

html5-qrcode 维护活跃,社区支持好。

  • 底层可能依赖 zxingjsqrcode 的变体。
  • 体积相对较大,但功能最全。
  • 适合大多数商业项目,减少自研成本。

qr-scanner 架构现代,性能最优。

  • 默认使用 Web Worker,不阻塞 UI 渲染。
  • 体积轻量,依赖少。
  • 适合对帧率敏感的应用(如游戏、互动营销)。

jsqr 核心算法库,稳定但需自行优化。

  • 无外部依赖,体积极小。
  • 性能取决于调用频率,需自行实现节流或 Worker 化。
  • 适合嵌入式场景或作为其他库的底层替代。

qrcode-reader 维护停滞,存在风险。

  • 基于早期的 jsqrcode 移植。
  • 解码速度和准确率不如现代库。
  • 明确建议:新项目中不应使用,仅用于遗留系统维护。

📊 总结与选型建议

特性html5-qrcodeqr-scannerjsqrqrcode-reader
相机管理✅ 自动✅ 自动❌ 手动❌ 手动
UI 组件✅ 内置❌ 无❌ 无❌ 无
多线程❌ 主线程✅ Web Worker❌ 主线程❌ 主线程
API 风格回调/PromisePromise/回调同步函数回调
维护状态🟢 活跃🟢 活跃🟡 稳定🔴 停滞

最终建议

  • 追求开发效率功能完整性,选 html5-qrcode
  • 追求运行性能轻量级,选 qr-scanner
  • 需要完全控制底层数据流,选 jsqr
  • qrcode-reader 请避免在新架构中使用。

如何选择: html5-qrcode vs jsqr vs qr-scanner vs qrcode-reader

  • html5-qrcode:

    选择 html5-qrcode 如果你需要快速落地功能,且希望库能自动处理相机权限、视频流绑定和基础 UI。它最适合后台管理系统、活动签到等需要快速集成扫描功能的场景,减少了底层媒体处理的样板代码。

  • jsqr:

    选择 jsqr 如果你已经拥有了图像数据(例如从 Canvas 提取或 WebSocket 传输),只需要纯粹的解码算法。它适合需要高度自定义视频采集逻辑、或在非标准视频流环境(如 WebRTC 自定义流)中工作的场景。

  • qr-scanner:

    选择 qr-scanner 如果你关注扫描性能和现代开发体验。它利用 Web Worker 避免阻塞主线程,API 设计简洁且基于 Promise,适合对交互流畅度要求高、且希望手动控制视频元素样式的现代 Web 应用。

  • qrcode-reader:

    避免在新项目中使用 qrcode-reader。它属于早期技术栈,缺乏对现代浏览器特性的优化,且维护活跃度低。仅在维护遗留系统且无法轻易替换解码核心时才考虑保留。

html5-qrcode的README

Html5-QRCode

Lightweight & cross platform QR Code and Bar code scanning library for the web

Use this lightweight library to easily / quickly integrate QR code, bar code, and other common code scanning capabilities to your web application.

Key highlights

Supports two kinds of APIs

  • Html5QrcodeScanner — End-to-end scanner with UI, integrate with less than ten lines of code.

  • Html5Qrcode — Powerful set of APIs you can use to build your UI without worrying about camera setup, handling permissions, reading codes, etc.

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.

CircleCI GitHub issues GitHub tag (latest by date) GitHub Codacy Badge Gitter

GitHub all releases npm

Demo at scanapp.orgDemo at qrcode.minhazav.dev - Scanning different types of codes

We need your help!

image Help incentivise feature development, bug fixing by supporting the sponsorhip goals of this project. See list of sponsered feature requests here.

ko-fi

Documentation

The documentation for this project has been moved to scanapp.org/html5-qrcode-docs.

Supported platforms

We 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 to test it out.

Legends

  • Means full support — inline webcam and file based
  • Means partial support — only file based, webcam in progress

PC / Mac

Firefox
Firefox
Chrome
Chrome
Safari
Safari
Opera
Opera
Edge
Edge

Android

Chrome
Chrome
Firefox
Firefox
Edge
Edge
Opera
Opera
Opera-Mini
Opera Mini
UC
UC

IOS

Safari
Safari
Chrome
Chrome
Firefox
Firefox
Edge
Edge
**

* Supported for IOS versions >= 15.1

Before version 15.1, 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

Framework support

The 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.

Html5VueJsElectronJsReactLit

Supported Code formats

Code scanning is dependent on Zxing-js 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.

CodeExample
QR Code
AZTEC
CODE_39
CODE_93
CODE_128
ITF
EAN_13
EAN_8
PDF_417
UPC_A
UPC_E
DATA_MATRIX
MAXICODE*
RSS_14*
RSS_EXPANDED*

*Formats are not supported by our experimental integration with native BarcodeDetector API integration (Read more).

Description - View Demo

See an end to end scanner experience at scanapp.org.

This 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.

Supports:

  • Querying camera on the device (with user permissions)
  • Rendering live camera feed, with easy to use user interface for scanning
  • Supports scanning a different kind of QR codes, bar codes and other formats
  • Supports selecting image files from the device for scanning codes

How to use

Find detailed guidelines on how to use this library on scanapp.org/html5-qrcode-docs.

Demo


Scan this image or visit blog.minhazav.dev/research/html5-qrcode.html

For more information

Check these articles on how to use this library:

Screenshots

screenshot
Figure: Screenshot from Google Chrome running on MacBook Pro

Documentation

Find the full API documentation at scanapp.org/html5-qrcode-docs/docs/apis.

Extra optional configuration in start() method

Configuration 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 {}.

fps — Integer, Example = 10

A.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.

qrboxQrDimensions or QrDimensionFunction (Optional), Example = { width: 250, height: 250 }

Use 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 : { width: 250, height: 250 } }, the screen will look like:

This can be used to set a rectangular scanning area with config like:

let config = { qrbox : { width: 400, height: 150 } }

This config also accepts a function of type

/**
  * A function that takes in the width and height of the video stream 
* and returns QrDimensions.
* 
* Viewfinder refers to the video showing camera stream.
*/
type QrDimensionFunction =
    (viewfinderWidth: number, viewfinderHeight: number) => QrDimensions;

This allows you to set dynamic QR box dimensions based on the video dimensions. See this blog article for example: Setting dynamic QR box size in Html5-qrcode - ScanApp blog

This might be desirable for bar code scanning.

If this value is not set, no shaded QR box will be rendered and the scanner will scan the entire area of video stream.

aspectRatio — Float, Example 1.777778 for 16:9 aspect ratio

Use 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:

ValueAspect RatioUse Case
1.3333344:3Standard camera aspect ratio
1.77777816:9Full screen, cinematic
1.01:1Square view

If you do not pass any value, the whole viewfinder would be used for scanning. Note: this value has to be smaller than the width and height of the QR code HTML element.

disableFlip — Boolean (Optional), default = false

By 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:

  • You are sure that the camera feed cannot be mirrored (Horizontally flipped)
  • You are facing performance issues with this enabled.

Here's an example of a normal and mirrored QR Code

Normal QR CodeMirrored QR Code

rememberLastUsedCamera — Boolean (Optional), default = true

If true the last camera used by the user and weather or not permission was granted would be remembered in the local storage. If the user has previously granted permissions — the request permission option in the UI will be skipped and the last selected camera would be launched automatically for scanning.

If true the library shall remember if the camera permissions were previously granted and what camera was last used. If the permissions is already granted for "camera", QR code scanning will automatically * start for previously used camera.

supportedScanTypes - Array<Html5QrcodeScanType> | []

This is only supported for Html5QrcodeScanner.

Default = [Html5QrcodeScanType.SCAN_TYPE_CAMERA, Html5QrcodeScanType.SCAN_TYPE_FILE]

This field can be used to:

  • Limit support to either of Camera or File based scan.
  • Change default scan type.

How to use:

function onScanSuccess(decodedText, decodedResult) {
  // handle the scanned code as you like, for example:
  console.log(`Code matched = ${decodedText}`, decodedResult);
}

let config = {
  fps: 10,
  qrbox: {width: 100, height: 100},
  rememberLastUsedCamera: true,
  // Only support camera scan type.
  supportedScanTypes: [Html5QrcodeScanType.SCAN_TYPE_CAMERA]
};

let html5QrcodeScanner = new Html5QrcodeScanner(
  "reader", config, /* verbose= */ false);
html5QrcodeScanner.render(onScanSuccess);

For file based scan only choose:

supportedScanTypes: [Html5QrcodeScanType.SCAN_TYPE_FILE]

For supporting both as it is today, you can ignore this field or set as:

supportedScanTypes: [
  Html5QrcodeScanType.SCAN_TYPE_CAMERA,
  Html5QrcodeScanType.SCAN_TYPE_FILE]

To set the file based scan as defult change the order:

supportedScanTypes: [
  Html5QrcodeScanType.SCAN_TYPE_FILE,
  Html5QrcodeScanType.SCAN_TYPE_CAMERA]

showTorchButtonIfSupported - boolean | undefined

This is only supported for Html5QrcodeScanner.

If true the rendered UI will have button to turn flash on or off based on device + browser support. The value is false by default.

Scanning only specific formats

By default, both camera stream and image files are scanned against all the supported code formats. Both Html5QrcodeScanner and Html5Qrcode classes can be configured to only support a subset of supported formats. Supported formats are defined in enum Html5QrcodeSupportedFormats.

enum Html5QrcodeSupportedFormats {
  QR_CODE = 0,
  AZTEC,
  CODABAR,
  CODE_39,
  CODE_93,
  CODE_128,
  DATA_MATRIX,
  MAXICODE,
  ITF,
  EAN_13,
  EAN_8,
  PDF_417,
  RSS_14,
  RSS_EXPANDED,
  UPC_A,
  UPC_E,
  UPC_EAN_EXTENSION,
}

I recommend using this only if you need to explicitly omit support for certain formats or want to reduce the number of scans done per second for performance reasons.

Scanning only QR code with Html5Qrcode

const html5QrCode = new Html5Qrcode(
  "reader", { formatsToSupport: [ Html5QrcodeSupportedFormats.QR_CODE ] });
const qrCodeSuccessCallback = (decodedText, decodedResult) => {
    /* handle success */
};
const config = { fps: 10, qrbox: { width: 250, height: 250 } };

// If you want to prefer front camera
html5QrCode.start({ facingMode: "user" }, config, qrCodeSuccessCallback);

Scanning only QR code and UPC codes with Html5QrcodeScanner

function onScanSuccess(decodedText, decodedResult) {
  // Handle the scanned code as you like, for example:
  console.log(`Code matched = ${decodedText}`, decodedResult);
}

const formatsToSupport = [
  Html5QrcodeSupportedFormats.QR_CODE,
  Html5QrcodeSupportedFormats.UPC_A,
  Html5QrcodeSupportedFormats.UPC_E,
  Html5QrcodeSupportedFormats.UPC_EAN_EXTENSION,
];
const html5QrcodeScanner = new Html5QrcodeScanner(
  "reader",
  {
    fps: 10,
    qrbox: { width: 250, height: 250 },
    formatsToSupport: formatsToSupport
  },
  /* verbose= */ false);
html5QrcodeScanner.render(onScanSuccess);

Experimental features

The library now supports some experimental features which are supported in the library but not recommended for production usage either due to limited testing done or limited compatibility for underlying APIs used. Read more about it here. Some experimental features include:

How to modify and build

  1. Code changes should only be made to /src only.

  2. Run npm install to install all dependencies.

  3. Run npm run-script build to build JavaScript output. The output JavaScript distribution is built to /dist/html5-qrcode.min.js. If you are developing on Windows OS, run npm run-script build-windows.

  4. Testing

    • Run npm test
    • Run the tests before sending a pull request, all tests should run.
    • Please add tests for new behaviors sent in PR.
  5. Send a pull request

    • Include code changes only to ./src. Do not change ./dist manually.
    • In the pull request add a comment like
    @all-contributors please add @mebjas for this new feature or tests
    
    • For calling out your contributions, the bot will update the contributions file.
    • Code will be built & published by the author in batches.

How to contribute

You can contribute to the project in several ways:

  • File issue ticket for any observed bug or compatibility issue with the project.
  • File feature request for missing features.
  • Take open bugs or feature request and work on it and send a Pull Request.
  • Write unit tests for existing codebase (which is not covered by tests today). Help wanted on this - read more.

Support 💖

This project would not be possible without all of our fantastic contributors and sponsors. If you'd like to support the maintenance and upkeep of this project you can donate via GitHub Sponsors.

Sponsor the project for priortising feature requests / bugs relevant to you. (Depends on scope of ask and bandwidth of the contributors).

webauthor@ ben-gy bujjivadu

Help incentivise feature development, bug fixing by supporting the sponsorhip goals of this project. See list of sponsered feature requests here.

Also, huge thanks to following organizations for non monitery sponsorships

Credits

The decoder used for the QR code reading is from Zxing-js https://github.com/zxing-js/library