2022-12-05 14:15:26 +08:00
|
|
|
import React from 'react';
|
2024-06-22 17:33:06 +08:00
|
|
|
import { Button, QRCode, Segmented, Space } from 'antd';
|
|
|
|
import type { QRCodeProps } from 'antd';
|
2022-12-05 14:15:26 +08:00
|
|
|
|
2024-06-22 17:33:06 +08:00
|
|
|
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 = () => {
|
2022-12-05 14:15:26 +08:00
|
|
|
const canvas = document.getElementById('myqrcode')?.querySelector<HTMLCanvasElement>('canvas');
|
|
|
|
if (canvas) {
|
|
|
|
const url = canvas.toDataURL();
|
2024-06-22 17:33:06 +08:00
|
|
|
doDownload(url, 'QRCode.png');
|
2022-12-05 14:15:26 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-06-22 17:33:06 +08:00
|
|
|
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']}
|
|
|
|
onChange={(val) => setRenderType(val as QRCodeProps['type'])}
|
|
|
|
/>
|
|
|
|
<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>
|
|
|
|
);
|
|
|
|
};
|
2022-12-05 14:15:26 +08:00
|
|
|
|
|
|
|
export default App;
|