@canvas-components/qrcode
v0.1.5
Published
Canvas QR code drawing and export utilities.
Readme
@canvas-components/qrcode
@canvas-components/qrcode 是一个纯原生的 Canvas 二维码绘制与导出工具包,适合卡片、海报、票据、表格单元格和导出场景。
功能作用
- 支持二维码矩阵编码和缓存读取
- 支持直接绘制到 Canvas
- 支持导出为 SVG、Data URL、Blob
- 支持容错等级、配色、静区、透明度配置
安装方法
pnpm add @canvas-components/qrcode最低环境要求:
Node.js >= 18.12.0pnpm >= 9.0.0
使用方法
import {
drawQrCodeToCanvas,
getQrCodeMatrix,
} from "@canvas-components/qrcode";
const canvas = document.querySelector("canvas")!;
const ctx = canvas.getContext("2d")!;
drawQrCodeToCanvas({
ctx,
x: 0,
y: 0,
width: 160,
height: 160,
value: "https://example.com",
level: "M",
});
const matrix = getQrCodeMatrix("https://example.com", "M");属性说明
DrawQrCodeToCanvasOptions
| 属性 | 类型 | 说明 |
| --- | --- | --- |
| ctx | CanvasRenderingContext2D \| OffscreenCanvasRenderingContext2D | 目标画布上下文 |
| x / y | number | 绘制起点 |
| width / height | number | 绘制区域尺寸,内部按较短边生成二维码主体 |
| value | string | 编码内容 |
| level | "L" \| "M" \| "Q" \| "H" | 容错等级 |
| color | string | 深色模块颜色 |
| backgroundColor | string | 背景色 |
| padding | number | 静区大小 |
| opacity | number | 透明度 |
QrCodeMatrix
| 属性 | 类型 | 说明 |
| --- | --- | --- |
| version | number | 二维码版本号 |
| size | number | 矩阵边长 |
| modules | boolean[][] | 最终深浅模块矩阵 |
ExportQrCodeToImageOptions
| 属性 | 类型 | 说明 |
| --- | --- | --- |
| pixelRatio | number | 位图导出倍率 |
| type | "image/png" \| "image/jpeg" \| "image/webp" | 导出类型 |
| quality | number | 图片质量 |
| canvas | ExportCanvasLike | 可复用外部 canvas |
方法说明
| 方法 | 签名 | 说明 |
| --- | --- | --- |
| encodeQrCodeMatrix | (value, level?) => QrCodeMatrix | 重新编码并返回新矩阵 |
| getQrCodeMatrix | (value, level?) => QrCodeMatrix | 带缓存读取矩阵,适合重复使用 |
| drawQrCodeToCanvas | (options) => void | 直接绘制到 canvas |
| exportQrCodeToSvg | (options) => string | 导出 SVG 字符串 |
| exportQrCodeToDataUrl | (options) => Promise<string> | 导出图片 Data URL |
| exportQrCodeToBlob | (options) => Promise<Blob> | 导出图片 Blob |
适用场景
- 海报、卡片、名片二维码
- 表格中的二维码单元格
- 前端离屏生成下载素材
- 票据、设备标识和面板角标
