html5-qrcode vs qr-scanner vs qrious
前端 QR 码处理方案:生成与扫描的技术选型
html5-qrcodeqr-scannerqrious类似的npm包:

前端 QR 码处理方案:生成与扫描的技术选型

html5-qrcodeqr-scanner 是专注于在浏览器中扫描二维码的库,支持摄像头和文件输入;而 qrious 则专注于生成二维码图像。这三者共同覆盖了 Web 应用中 QR 码的完整生命周期,但各自侧重点不同。html5-qrcode 提供全面的扫描功能和良好的兼容性,qr-scanner 以轻量和高性能著称,qrious 则是生成二维码的简洁方案。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
html5-qrcode06,1352.63 MB4353 年前Apache-2.0
qr-scanner02,868524 kB118-MIT
qrious01,625-439 年前GPL-3.0

前端 QR 码处理方案:生成与扫描的技术选型

在 Web 应用中处理 QR 码通常涉及两个截然不同的方向:生成(Writing)和扫描(Reading)。html5-qrcodeqr-scannerqrious 是 npm 生态中三个热门选择,但它们的职责并不完全重叠。qrious 专注于生成,而 html5-qrcodeqr-scanner 专注于扫描。作为架构师,理解它们的底层差异对于构建高效、可维护的 QR 码功能至关重要。

🛠️ 初始化与集成模式

这三个库都设计为易于集成,但它们的实例化方式反映了不同的设计哲学。

html5-qrcode 需要一个 DOM 元素的 ID 来绑定扫描器视图。

  • 它内部管理视频元素和画布。
  • 适合快速集成,但耦合了 DOM 结构。
// html5-qrcode: 绑定到现有 DOM 元素
import { Html5Qrcode } from "html5-qrcode";

const html5QrCode = new Html5Qrcode("reader-div-id");

qr-scanner 更加灵活,可以直接接受视频元素或约束条件。

  • 它不强制要求特定的容器 ID。
  • 适合需要自定义 UI 或复杂布局的场景。
// qr-scanner: 传入视频元素或配置
import QrScanner from "qr-scanner";

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

qrious 专注于 Canvas 元素,用于绘制二维码。

  • 它不处理摄像头或输入流。
  • 初始化时直接配置内容和样式。
// qrious: 基于 Canvas 生成
import QRious from "qrious";

const qr = new QRious({
  element: document.getElementById("canvas"),
  value: "https://example.com"
});

🎯 核心功能实现:扫描 vs 生成

这是选择库时的决定性因素。你需要明确你的应用是需要“读”还是“写”。

html5-qrcode 提供完整的扫描流程控制。

  • 支持启动、停止、暂停摄像头。
  • 支持从本地文件扫描图片。
// html5-qrcode: 启动摄像头扫描
html5QrCode.start(
  { facingMode: "environment" },
  { fps: 10, qrbox: 250 },
  onScanSuccess,
  onScanFailure
);

qr-scanner 专注于快速解码视频流或单张图片。

  • API 更偏向 Promise 风格。
  • 适合单次扫描或自定义循环逻辑。
// qr-scanner: 扫描单张图片或视频流
import QrScanner from "qr-scanner";

// 扫描图片
const result = await QrScanner.scanImage(fileInput.files[0]);

// 或启动视频流监听
scanner.start();

qrious 仅用于生成二维码图像。

  • 不支持任何扫描功能。
  • 可以动态更新内容并重新绘制。
// qrious: 生成二维码
qr.set({ value: "New Content" });
// 或者导出为图片
const dataURL = qr.toDataURL();

📡 回调与事件处理

处理扫描结果或生成状态的方式直接影响代码的可读性和错误处理。

html5-qrcode 使用独立的回调函数处理成功和失败。

  • 成功时返回解码后的文本。
  • 失败时频繁触发(例如每帧未检测到码),需防抖处理。
// html5-qrcode: 独立回调
function onScanSuccess(decodedText) {
  console.log(`扫描成功:${decodedText}`);
}

function onScanFailure(error) {
  // 注意:这可能会高频触发
  console.warn(`扫描失败:${error}`);
}

qr-scanner 在构造函数或事件中返回 Promise 或回调。

  • 更现代的异步处理方式。
  • 错误处理更符合标准 Promise 链。
// qr-scanner: Promise 或事件回调
scanner.onresult = event => {
  console.log(`扫描结果:${event.code}`);
};

scanner.onerror = error => {
  console.error(error);
};

qrious 是同步操作,不需要异步回调。

  • 设置值后立即更新 Canvas。
  • 错误通常在初始化时抛出。
// qrious: 同步设置
try {
  qr.set({ value: "data" });
} catch (e) {
  console.error("生成失败", e);
}

⚙️ 底层技术与性能

了解底层实现有助于预测性能瓶颈和兼容性。

html5-qrcode 基于 ZXing 库的 Web 移植版。

  • 兼容性好,支持多种码制。
  • 相对较重,因为包含了完整的解码逻辑。
// html5-qrcode: 配置解码器
// 内部使用 zxing-js 库,无需额外配置即可支持 QR, Aztec 等

qr-scanner 使用 WebAssembly 和 Web Workers。

  • 将繁重的解码任务移出主线程。
  • 性能更优,UI 阻塞更少。
// qr-scanner: 自动使用 Worker
// 需确保 worker 文件正确加载到 public 目录
// import QrScanner from "qr-scanner";
// QrScanner.WORKER_PATH = "/qr-scanner-worker.min.js";

qrious 纯 JavaScript 实现,基于 Canvas API。

  • 无外部重型依赖。
  • 生成速度极快,适合高频动态更新。
// qrious: 轻量级生成
// 无 Worker 需求,主线程执行即可,因为计算量小

📊 总结对比表

特性html5-qrcodeqr-scannerqrious
主要用途🔍 扫描 (摄像头 + 文件)🔍 扫描 (高性能)✍️ 生成
底层技术ZXing (JS)WebAssembly + WorkerCanvas API
API 风格回调函数Promise / 事件同步配置
UI 耦合高 (管理容器)低 (传入元素)中 (Canvas)
线程模型主线程Web Worker主线程
适用场景企业后台、兼容优先C 端应用、性能优先凭证生成、分享码

💡 架构建议

html5-qrcode 像是一把瑞士军刀 🔪 — 功能全面,兼容性强,适合需要快速落地且对体积不敏感的项目。如果你的目标是“确保在所有设备上都能扫”,选它。

qr-scanner 像是一把手术刀 🏳️ — 精准、快速、轻量。适合对用户体验要求极高,且可以控制浏览器版本范围的现代 Web 应用。

qrious 像是一支打印笔 🖊️ — 专门用于创建。在任何需要展示 QR 码的场景中,它都是生成端的首选。

最终建议:在实际架构中,你很可能需要组合使用。使用 qrious 生成业务二维码,使用 html5-qrcodeqr-scanner 提供扫描入口。不要试图用一个库解决所有问题,根据“读”与“写”的需求分开选型是更稳健的决策。

如何选择: html5-qrcode vs qr-scanner vs qrious

  • html5-qrcode:

    选择 html5-qrcode 如果你需要广泛的浏览器兼容性,并且希望一个库同时支持摄像头实时扫描和本地文件上传扫描。它适合企业级应用,其中稳定性和功能完整性比包大小更重要,且你需要开箱即用的 UI 容器管理。

  • qr-scanner:

    选择 qr-scanner 如果你追求极致的性能和更小的打包体积,且主要面向现代浏览器环境。它适合对加载速度敏感的消费级应用,或者你需要更灵活地自定义视频流处理逻辑而不依赖库内置的 UI 容器。

  • qrious:

    选择 qrious 如果你的需求是生成二维码而不是扫描。它适合需要在客户端动态创建二维码图像的场景,例如生成分享链接、票务凭证或用户身份码,且你希望直接操作 Canvas 或获取 Data URL。

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