二维码
给画布插入二维码并实时修改内容,是电商优惠券、邀请函、名片类设计的高频需求。思路很简单:
添加一个二维码
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>
);
});
把它做成一个侧边面板
把上面的 addQRCode 和 QRCodeEditor 组合成一个自定义 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'打开
相关文档
- 👉 元素操作 ——
addElement/store.set/selectedElements - 👉 工具函数 · svg ——
svgToURL - 👉 自定义 Section —— 如何把本案例做成侧边面板