在vue 中使用html2canvas 遇到的坑

本文分享了在Vue项目中使用html2canvas组件时遇到的问题及解决方案,包括避免使用百分比宽度和背景图片等,确保生成图片的质量。

在vue 中使用html2canvas 遇到的坑

文档: html2canvas.hertzen.com/features

坑1 需要绘制的部分的 (原生)dom 对象 ,注意容器的宽度不要使用百分比,使用固定宽度,避免缩放问题

坑2 !! 不要使用背景图片 , 可能是我点背,,,主要是这引起的报错

建议使用最新版

<div  v-longpress="convert2canvas" :class="['moon-detail_block',this.$mn.Code]" id="shareContent" ref="referee">
  <div class="referee_wrap" :style="moon_Referee_obj">
    <img :src="currentSrc" alt="">
    <div class="referee_header" flex="cross:center dir:top">
        <div class="referee_tit">
          送你一张万能服
        </div>
        <div class="qrCode">
        </div>
      <div class="con">

      </div>
    </div>
  </div>
</div>
复制代码
methods
  convert2canvas(e) {
      console.log(e, "eeee,C2222222222CANVEWFW");
      console.log(this.$refs.referee, "refs");
      console.log(this.$mount, "mout");
      var shareContent = document.getElementById("shareContent"); // 需要绘制的部分的 (原生)dom 对象 ,注意容器的宽度不要使用百分比,使用固定宽度,避免缩放问题
      var width = shareContent.offsetWidth; // 获取(原生)dom 宽度
      var height = shareContent.offsetHeight; // 获取(原生)dom 高
      var offsetTop = shareContent.offsetTop; //元素距离顶部的偏移量

      var canvas = document.createElement("canvas"); //创建canvas 对象
      var context = canvas.getContext("2d");
      var scaleBy = this.getPixelRatio(context); //获取像素密度的方法 (也可以采用自定义缩放比例)
      canvas.width = width * scaleBy; //这里 由于绘制的dom 为固定宽度,居中,所以没有偏移
      canvas.height = (height + offsetTop) * scaleBy; // 注意高度问题,由于顶部有个距离所以要加上顶部的距离,解决图像高度偏移问题
      context.scale(scaleBy, scaleBy);

      var opts = {
        allowTaint: true, //允许加载跨域的图片
        tainttest: true, //检测每张图片都已经加载完成
        scale: scaleBy, // 添加的scale 参数
        canvas: canvas, //自定义 canvas
        logging: true, //日志开关,发布的时候记得改成false
        width: width, //dom 原始宽度
        height: height //dom 原始高度
      };
      html2canvas(shareContent, opts).then(function(canvas) {
        console.log("html2canvas");
        console.log(canvas, "222222");
        var body = document.getElementsByTagName("body");
        body[0].appendChild(canvas);
      });
    },
      //获取像素密度
    getPixelRatio: function(context) {
      var backingStore =
        context.backingStorePixelRatio ||
        context.webkitBackingStorePixelRatio ||
        context.mozBackingStorePixelRatio ||
        context.msBackingStorePixelRatio ||
        context.oBackingStorePixelRatio ||
        context.backingStorePixelRatio ||
        1;
      return (window.devicePixelRatio || 1) / backingStore;
    },
复制代码
mounted() {
    this.convert2canvas();
  },
复制代码
长按指令
 directives: {
    longpress: {
      inserted: function(el) {
        console.log(el, "longpress");
      },
      bind: function(el, binding, vNode) {
        console.log(vNode, "bind");
        let pressTimer = null;

        // 定义函数处理程序
        // 创建计时器( 1秒后执行函数 )
        let start = e => {
          console.log(e, "eeeeeee");
          if (e.type === "click" && e.button !== 0) {
            return;
          }

          if (pressTimer === null) {
            pressTimer = setTimeout(() => {
              // 执行函数 长按
              handler();
            }, 1000);
          }
        };

        // 取消计时器
        let cancel = e => {
          // 检查计时器是否有值
          if (pressTimer !== null) {
            clearTimeout(pressTimer);
            pressTimer = null;
          }
        };

        // 运行函数
        const handler = e => {
          // 执行传递给指令的方法
          console.log(binding, "binding");
          binding.value(e);
        };

        // 添加事件监听器
        el.addEventListener("mousedown", start);
        el.addEventListener("touchstart", start);

        // 取消计时器
        el.addEventListener("click", cancel);
        el.addEventListener("mouseout", cancel);
        el.addEventListener("touchend", cancel);
        el.addEventListener("touchcancel", cancel);
      }
    }
  },
复制代码

转载于:https://juejin.im/post/5b7bd566e51d45597f5a2d47

### 安装 html2canvasVue3 项目中使用 `html2canvas`,首先需要通过 npm 或 yarn 安装该库: ```bash npm install html2canvas ``` 或 ```bash yarn add html2canvas ``` 安装完成后,在需要使用的组件中引入: ```javascript import html2canvas from 'html2canvas'; ``` ### 使用 html2canvas 生成图片 在 Vue3 中,可以通过 `ref` 获取 DOM 节点,并将其转换为图片。以下是一个示例方法,用于将指定 DOM 元素生成图片并提供下载功能: ```javascript export default { methods: { generateImage() { const dom = document.getElementById('capture'); // 获取需要生成图片的 DOM 节点 html2canvas(dom, { backgroundColor: null, // 保持背景透明 useCORS: true, // 支持跨域资源 scale: window.devicePixelRatio // 提高图片清晰度 }).then((canvas) => { const imageUrl = canvas.toDataURL('image/png'); // 将 canvas 转换为图片链接 this.downloadImage(imageUrl, 'generated-image'); }).catch((err) => { console.error('生成图片失败:', err); }); }, downloadImage(downloadUrl, downloadName) { const link = document.createElement('a'); link.style.display = 'none'; link.href = downloadUrl; link.download = `${downloadName}.png`; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } } ``` 在页面中添加一个用于测试的 DOM 节点和一个按钮: ```html <template> <div> <div id="capture" style="width: 300px; height: 200px; background-color: lightblue;"> <p>这是一个测试区域</p> </div> <button @click="generateImage">生成图片并下载</button> </div> </template> ``` ### 处理移动端兼容性问题 在移动端使用 `html2canvas` 时,可能会遇到 iOS 设备截图失效的问题。为了解决这一问题,可以调整 `html2canvas` 的配置,使用 `window.devicePixelRatio` 提高图片清晰度,并确保正确设置 `scale`、`useCORS` 等参数: ```javascript html2canvas(dom, { scale: window.devicePixelRatio, useCORS: true, width: dom.clientWidth, height: dom.clientHeight, x: 0, y: 0 }).then((canvas) => { const url = canvas.toDataURL("image/png"); this.picUrl = url; }).catch((err) => { console.error('生成图片时发生错误:', err); }); ``` ### 总结 通过上述步骤,可以在 Vue3 项目中使用 `html2canvas` 将 DOM 元素转换为图片,并提供下载功能。同时,通过合理配置 `scale` 和 `useCORS`,可以提升图片质量并解决移动端兼容性问题[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值