1、下载npm包
yarn add qrcode
yarn add @types/qrcode
2、React 组件
import QRCode from "qrcode";
const QRCodeBox = ({ value, width = 190, color = '#000', light = '#fff', qrSize = 180, qrText = '', qrTextSize = 14, }) =>{
const qrCodeOption: any = {
errorCorrectionLevel: "H",
width: width,
version: 7,
margin: 6,
color: {
dark: color,
light: light
}
};
const handleQRcode = () => {
let dom = document.getElementById('canvas')
if (dom) {
QRCode.toDataURL(value, qrCodeOption).then((url: string) => {
const ctx = dom.getContext("2d") as CanvasRenderingContext2D;
const image = new Image();
image.src = url;
new Promise<HTMLImageElement>((resolve) => {
image.onload = () => {
resolve(image);
};
}).then((img: HTMLImageElement) => {
ctx.drawImage(img, (width - qrSize) / 2, 0, qrSize, qrSize);
if (qrText) {
ctx.font = "bold " + qrTextSize + "px Arial";
let tw = ctx.measureText(qrText).width;
let ftop = qrSize - qrTextSize;
let fleft = (width - tw) / 2;
ctx.textBaseline = "top";
ctx.fillStyle = "#333";
ctx.fillText(qrText, fleft, ftop);
}
console.log(dom.toDataURL("image/png", 1))
})
}).catch((err: Error) => {
console.error(err);
});
}
}
useEffect(() => {
if (value) handleQRcode()
}, [value])
return (
<canvas id="canvas" className='canvas' width={width} height={width} />
)
}
3、qrcode 文档地址
github.com/soldair/nod…