目录

html2canvas海报生成

Admin5/31/20221356 阅读

引用方法

vue

shell 复制代码
npm i -S html2canvas file-saver
shell 复制代码
import html2canvas from \"html2canvas\";
//import FileSaver from \"file-saver\";

使用方法

language 复制代码
  <div class=\"invitation\" id=\"invitation\" v-if=\"!showImg\">
    <img
      src=\"https://cdn.aicl.space/aici_space_service_img/invites1.jpg\"
      class=\"bg-img\"
    />
    <div class=\"personal\">
      <van-image
        round
        width=\"35px\"
        height=\"35px\"
        :src=\"userInfo.collectionImgUrl\"
      />
      <span>{{ userInfo.username }}</span>
    </div>
    <div class=\"qrcode-img\">
      <qrcode-vue
        :value=\"`${url}?inviteCode=${loginInfo.userId}`\"
        :size=\"80\"
        level=\"H\"
      />
    </div>
  </div>
js 复制代码
onMounted(() => {
  handleExport();
});

//屏幕截图
const handleExport = () => {
  nextTick(() => {
    // 校正截图不全问题
    window.pageYOffset = 0;
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
    const postersDom = document.getElementById(\"invitation\") as HTMLElement;
    let width = postersDom.offsetWidth;
    let height = postersDom.offsetHeight;
    let canvas = document.createElement(\"canvas\");
    //定义任意放大倍数 支持小数,默认获取浏览器缩放比例
    const scale = window.devicePixelRatio;
    //定义canvas 宽度 * 缩放   高度 * 缩放
    canvas.width = width * scale;
    canvas.height = height * scale;
    let opts = {
      // 注意:  allowTaint: true  和 useCORS: true 不能同时设置,两者只有一个起作用
      scale: scale,
      canvas: canvas, //自定义 canvas
      // allowTaint: true, // 允许污染,允许画布上有跨域图片 不建议使用 后面详细补充
      logging: true, //日志开关,便于查看html2canvas的内部执行流程
      width: width, //dom 原始宽度
      height: height,
      dpi: 300,
      useCORS: true, // 【重要】开启跨域配置
      letterRendering: true,
    };

    html2canvas(postersDom, opts).then((canvas) => {
      posterUrl.value = canvas.toDataURL(\"image/png\");
      showImg.value = true;
    });
  });
};

常见问题

图片模糊

不要使用背景图片,改用img显示

评论

共 0 条
后参与评论
共 104 篇文章 感谢支持

RSS ·关于

© 2026 我的博客