前端使用 qrcode 与 html2canvas 生成二维码并导出

在实际开发中,我们有可能需要根据数据生成二维码的功能模块。前后端都是可以实现的,但是前端相对更灵活一些。

1 需要用到的前端 js 库 qrcode html2canvas

npm install qrcode // 生成二维码

npm install html2canvas  // 将html元素绘制成图片

2 React 实例

import QRCode from 'qrcode';
import html2canvas from "html2canvas";

const View = () => {
    
    
  const handleClickExport = async () => {
    
    
    const canvas = await html2canvas(dom as HTMLElement)
    let a = document.createElement("a");
    document.body.appendChild(a);
    a.setAttribute("href", canvas.toDataURL("image/jpg", 1.0));
    a.setAttribute("download", "text.png");
    a.setAttribute("target", "_self");
    a.click();
    document.body.removeChild(a);
    document.body.removeChild(dom);
  }

  return (
    <Button onClick={
    
    handleClickExport} > 生成二维码并导出 </Button>
  )
}

export default View

猜你喜欢

转载自blog.csdn.net/qq_53931766/article/details/128084114
今日推荐