html2canvas海报生成

2022-05-31 10:24:11
2024-04-15 19:51:27

引用方法

vue

npm i -S html2canvas file-saver
import html2canvas from "html2canvas";
//import FileSaver from "file-saver";

使用方法

  <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>
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显示

目录
暂无评论,欢迎留下你的评论

运营需要亿点资金维持,您的支持,是小白龙创作的动力!!!

昵称
留言
赞赏金额