我试图从react-qr-code
库下载生成的QRCode,但我在实际下载图像的步骤中卡住了。
import QRCode from "react-qr-code";
字符串
我在React组件中生成QRCode,如下所示:
return(
.
.
.
<QRCode id="qrcode" level="H" value={box.id} size={100} />
<Button onClick={downloadQRCode}>Download QR</Button>
);
型
我的下载功能:
const downloadQRCode = () => {
const canvas = document.getElementById("qrcode") as HTMLCanvasElement;
if (!canvas) throw new Error("Canvas not found");
const pngUrl = canvas
.toDataURL("image/png")
.replace("image/png", "image/octet-stream");
let downloadLink = document.createElement("a");
downloadLink.href = pngUrl;
downloadLink.download = `${box.id}.png`;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
};
型
如果我在尝试toDataURL
之前console.log(canvas)
,它得到了正确的svg。然而,当我运行downloadQRCode
函数时,我得到的是:
Uncaught TypeError: canvas.toDataURL is not a function
型
1条答案
按热度按时间ig9co6j11#
我通过将库从
react-qr-code
切换到qrcode.react
来使它工作,react-qr-code
似乎不是最好的库。这允许我使用
<QRCodeCanvas/>
和<QRCodeSVG/>
元素。使用
QRCodeCanvas
就像在评论中建议的那样解决了这个问题。字符串