File size: 1,658 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import React from 'react';
import { Button, QRCode, Segmented, Space } from 'antd';
import type { QRCodeProps } from 'antd';
function doDownload(url: string, fileName: string) {
const a = document.createElement('a');
a.download = fileName;
a.href = url;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
const downloadCanvasQRCode = () => {
const canvas = document.getElementById('myqrcode')?.querySelector<HTMLCanvasElement>('canvas');
if (canvas) {
const url = canvas.toDataURL();
doDownload(url, 'QRCode.png');
}
};
const downloadSvgQRCode = () => {
const svg = document.getElementById('myqrcode')?.querySelector<SVGElement>('svg');
const svgData = new XMLSerializer().serializeToString(svg!);
const blob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(blob);
doDownload(url, 'QRCode.svg');
};
const App: React.FC = () => {
const [renderType, setRenderType] = React.useState<QRCodeProps['type']>('canvas');
return (
<Space id="myqrcode" direction="vertical">
<Segmented options={['canvas', 'svg']} value={renderType} onChange={setRenderType} />
<div>
<QRCode
type={renderType}
value="https://ant.design/"
bgColor="#fff"
style={{ marginBottom: 16 }}
icon="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg"
/>
<Button
type="primary"
onClick={renderType === 'canvas' ? downloadCanvasQRCode : downloadSvgQRCode}
>
Download
</Button>
</div>
</Space>
);
};
export default App;
|