条形码(Barcode)
条形码元素用于在画布上生成一维条码,支持 CODE128、EAN13 等多种格式。常用于商品标签、物流单号等场景。
安装
typescript
import { BarcodePlugin } from 'vkedit'
host.installPlugin('barcode-plugin', BarcodePlugin)安装后,工具栏会显示条形码按钮。点击按钮后即可在画布上创建默认条形码。
通过代码创建
typescript
import { AddElementCommand } from 'vkedit'
const elementManager = host.getPlugin('element-manager-plugin')
const barcode = elementManager.createElement('barcode')
// 设置位置(毫米)
barcode.xmm = 10
barcode.ymm = 10
// 设置内容
barcode.content = '123456789012'
barcode.format = 'CODE128'
// 设置颜色
barcode.foreground = '#000000'
barcode.background = '#ffffff'
// 设置条码尺寸
barcode.barcodeHeightMM = 8 // 条码高度(毫米)
barcode.barcodeWidthMM = 0.2 // 单条纹宽度(毫米)
// 设置文字
barcode.displayValue = true
barcode.fontSizeMM = 3 // 文字字号(毫米)
barcode.marginMM = 0.2 // 边距(毫米)
host.executeCommand(new AddElementCommand(host, barcode))支持的格式
格式由 JsBarcode 库提供,常用格式包括:
| 格式 | 说明 | 内容限制 |
|---|---|---|
CODE128 | 通用格式(默认) | 支持字母、数字、符号 |
CODE39 | 工业用格式 | 大写字母、数字、特殊符号 |
EAN13 | 国际商品码 | 12-13 位数字 |
EAN8 | 短商品码 | 7-8 位数字 |
UPC | 北美商品码 | 11-12 位数字 |
typescript
// EAN13 格式(内容需为 12 或 13 位数字)
barcode.content = '690123456789'
barcode.format = 'EAN13'属性
基础属性(继承自 BaseGraphicElement)
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
xmm | number | 5 | X 坐标(毫米) |
ymm | number | 5 | Y 坐标(毫米) |
rotation | number | 0 | 旋转角度(度) |
visible | boolean | true | 是否可见 |
条码宽高自动计算
条码元素的 wmm 和 hmm 在渲染后由 JsBarcode 自动计算(基于内容长度和条纹宽度),不应手动设置。
条形码特有属性
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
content | string | '123456789012' | 编码内容 |
format | string | 'CODE128' | 条码格式 |
foreground | string | '#000000' | 前景色(条纹颜色) |
background | string | '#ffffff' | 背景色 |
displayValue | boolean | true | 是否显示文字内容 |
fontSizeMM | number | 3 | 文字字号(毫米) |
marginMM | number | 0.2 | 边距(毫米) |
barcodeHeightMM | number | 8 | 条码高度(毫米) |
barcodeWidthMM | number | 0.2 | 单条纹宽度(毫米) |
内容长度限制
不同格式对内容长度有严格要求。EAN13 需要 12-13 位数字,EAN8 需要 7-8 位数字。内容不符合规范时条码将无法生成。