跳到主要内容

二维码

给画布插入二维码并实时修改内容,是电商优惠券、邀请函、名片类设计的高频需求。思路很简单:

  1. qrcode 库把字符串生成 SVG
  2. svgToURL 转成 dataURL,作为 Image 元素插入画布
  3. 在元素上自定义字段保存原始文本,便于修改时重新生成

添加一个二维码

import QRCode from 'qrcode';
import { svgToURL } from '@ydesign/react-editor/utils/svg';
import { generateObjectId } from '@ydesign/core';

async function addQRCode(store: any, text: string) {
// 1) 生成 SVG 字符串
const svgStr = await QRCode.toString(text, {
type: 'svg',
color: { dark: '#000', light: '#fff' },
width: 400,
margin: 2,
});

// 2) 转 dataURL
const src = svgToURL(svgStr);

// 3) 作为 Image 元素加入画布
store.addElement({
id: generateObjectId(),
type: 'Image',
src,
left: 100,
top: 100,
width: 400,
height: 400,
custom: { qrText: text }, // 👈 关键:把原始文本存进 custom 字段
});
}

// 用法
addQRCode(store, 'https://ydesign.com');

选中后修改内容并重新生成

import { observer } from 'mobx-react-lite';
import { Input } from 'antd';
import QRCode from 'qrcode';
import { svgToURL } from '@ydesign/react-editor/utils/svg';

const QRCodeEditor = observer(({ store }) => {
const el = store.selectedElements[0];
if (!el?.custom?.qrText) return null; // 只在选中二维码时显示

const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const text = e.target.value;
const svgStr = await QRCode.toString(text, {
type: 'svg',
color: { dark: '#000', light: '#fff' },
width: el.width,
margin: 2,
});

// 一次性更新 src 和 custom.qrText
store.set(
{
src: svgToURL(svgStr),
custom: { qrText: text },
},
el,
);
};

return (
<div style={{ padding: 12 }}>
<div>二维码内容:</div>
<Input value={el.custom.qrText} onChange={handleChange} />
</div>
);
});

把它做成一个侧边面板

把上面的 addQRCodeQRCodeEditor 组合成一个自定义 Section,详见自定义 Section

import type { Section } from '@ydesign/react-editor/side-panel';
import { QrCode } from 'lucide-react';

const QRCodeSection: Section = {
name: 'qrcode',
Tab: /* ... 带 QrCode 图标的 SectionTab ... */,
Panel: observer(({ store }) => (
<div>
<Button onClick={() => addQRCode(store, 'https://ydesign.com')}>
添加二维码
</Button>
<QRCodeEditor store={store} />
</div>
)),
};

// 注册到 SidePanel
<SidePanel store={store} sections={[...DEFAULT_SECTIONS, QRCodeSection]} />;

关键点

  • custom 字段:Fabric 元素的扩展位,随 store.toJSON() 一起序列化,关闭再打开设计稿时还能正确修改二维码
  • SVG + dataURL:保证二维码无限清晰,导出为 PDF / 高倍 PNG 不会模糊
  • 纠错等级qrcode 库默认是 M 级,品牌设计如果要加 Logo,把 errorCorrectionLevel: 'H' 打开

相关文档