@canvas-components/barcode
v0.1.5
Published
Canvas barcode drawing and export utilities.
Readme
@canvas-components/barcode
@canvas-components/barcode 是一个纯原生的 Canvas 条形码绘制与导出工具包,适合在表格单元格、卡片、票据、打印标签和离屏导出场景中使用。
功能作用
- 支持
code128、code128b、code128c、code39、itf、ean13、ean8、upca - 支持直接绘制到
CanvasRenderingContext2D - 支持导出为 SVG、Data URL、Blob
- 支持自定义文本、颜色、间距、透明度和导出倍率
安装方法
pnpm add @canvas-components/barcode最低环境要求:
Node.js >= 18.12.0pnpm >= 9.0.0
使用方法
import {
drawBarcodeToCanvas,
exportBarcodeToSvg,
} from "@canvas-components/barcode";
const canvas = document.querySelector("canvas")!;
const ctx = canvas.getContext("2d")!;
drawBarcodeToCanvas({
ctx,
x: 0,
y: 0,
width: 240,
height: 72,
value: "123456789012",
format: "code128",
displayValue: true,
});
const svg = exportBarcodeToSvg({
value: "123456789012",
width: 240,
height: 72,
});属性说明
DrawBarcodeToCanvasOptions
| 属性 | 类型 | 说明 |
| --- | --- | --- |
| ctx | CanvasRenderingContext2D \| OffscreenCanvasRenderingContext2D | 目标画布上下文 |
| x / y | number | 绘制起点 |
| width / height | number | 绘制区域尺寸 |
| value | string | 原始编码值 |
| format | BarcodeFormat | 条形码制式,默认 code128 |
| color | string | 条纹前景色 |
| backgroundColor | string | 背景色 |
| padding | number | 内边距 |
| opacity | number | 透明度 |
| displayValue | boolean | 是否显示可读文本 |
| text | string | 自定义可读文本 |
| fontSize | number | 文本字号 |
| fontWeight | string | 文本字重 |
| fontFamily | string | 文本字体 |
| textColor | string | 文本颜色 |
| textGap | number | 条纹与文本间距 |
BarcodePattern
| 属性 | 类型 | 说明 |
| --- | --- | --- |
| format | BarcodeFormat | 实际使用的编码制式 |
| value | string | 原始输入值 |
| text | string | 最终可读文本 |
| codeValues | number[] | 中间编码值 |
| modules | number[] | 绘制用模块宽度序列 |
| moduleCount | number | 总模块数 |
ExportBarcodeToImageOptions
继承 DrawBarcodeToCanvasOptions 的大部分导出相关字段,另补充:
| 属性 | 类型 | 说明 |
| --- | --- | --- |
| pixelRatio | number | 位图导出倍率 |
| type | "image/png" \| "image/jpeg" \| "image/webp" | 导出图片类型 |
| quality | number | 图片质量 |
| canvas | ExportCanvasLike | 外部复用 canvas |
方法说明
| 方法 | 签名 | 说明 |
| --- | --- | --- |
| encodeBarcodePattern | (value, format?) => BarcodePattern | 把原始值编码为可绘制 pattern |
| drawBarcodeToCanvas | (options) => void | 直接绘制到 canvas |
| exportBarcodeToSvg | (options) => string | 导出 SVG 字符串 |
| exportBarcodeToDataUrl | (options) => Promise<string> | 导出图片 Data URL |
| exportBarcodeToBlob | (options) => Promise<Blob> | 导出图片 Blob |
适用场景
- 物流面单、仓储标签
- 表格中的条形码单元格
- 打印前预览与离屏导出
- 前端纯浏览器生成编码图片
