关于canvas:html2canvas将dom转换为画布

49次阅读

共计 1952 个字符,预计需要花费 5 分钟才能阅读完成。

以下是依赖于 html2canvas 生成的海报成果,亲测无效

以一张背景图 + 二维码的布局为例

html 局部:

  <div class="container">
    <div class="share-img">
      <img style="width: 300px; height: 300px" :src="imgUrl" alt="分享图" />
    </div>
    <div class="creat-img" ref="box">
      <img
        src="https://img0.baidu.com/it/u=3998012246,2453684564&fm=26&fmt=auto&gp=0.jpg"
        alt="分享背景图"
      />
      <div id="qrcode" class="qrcode"></div>
    </div>
  </div>

大抵是 share-img 这个盒子用来寄存最终生成的 canvas 海报
creat-img 盒子是寄存原始 dom 背景图和二维码的构造布局,下边通过 html2canvas 将其转换为画布海报

js 局部:

<script>
import {qrcanvas} from "qrcanvas";
import html2canvas from "html2canvas";
export default {data() {
    return {imgUrl: "",};
  },
  watch: {imgUrl(val, oldval) {
      // 监听到 imgUrl 有变动当前 阐明新图片曾经生成 暗藏 DOM
      this.$refs.box.style.display = "none";
    },
  },
  mounted() {
    let that = this;
    that.$nextTick(function () {
      // 生成二维码
      var canvas1 = qrcanvas({data: decodeURIComponent("https://www.baidu.com/"),// 你的二维码条跳转地址
        size: 128,
      });
      document.getElementById("qrcode").innerHTML = "";
      document.getElementById("qrcode").appendChild(canvas1);

      // 合成分享图
      html2canvas(that.$refs.box).then(function (canvas) {
          that.imgUrl = URL.createObjectURL(that.base64ToBlob(canvas.toDataURL())
          );
          // ios 的话会存在还未加载完就进行绘制,若为 ios 则放到定时器里执行
          // setTimeout(() => {}, 2000);
        }
      );
    });
  },

  methods: {
    //base64 转 blob
    base64ToBlob(code) {let parts = code.split(";base64,");
      let contentType = parts[0].split(":")[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;

      let uInt8Array = new Uint8Array(rawLength);

      for (let i = 0; i < rawLength; ++i) {uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], {type: contentType});
    },
  },
};
</script>

css 局部

<style lang='scss' scoped>
.creat-img {
  width: 300px;
  position: relative;
  height: 300px;
  img {
    width: 100%;
    height: 100%;
    z-index: 3;
  }
  .qrcode {
    position: absolute;
    bottom: 0rem;
    left: 75%;
    margin-left: -64px;
    z-index: 5;
  }
}
</style>

留神:html2canvas 绘制的时候要加跨域解决,否则绘制出的图片为空白的:加上
{allowTaint: false, useCORS: true}

      html2canvas(that.$refs.box, { allowTaint: false, useCORS: true}).then(function (canvas) {
          that.imgUrl = URL.createObjectURL(that.base64ToBlob(canvas.toDataURL())
          );
          // ios 的话会存在还未加载完就进行绘制,若为 ios 则放到定时器里执行
          // setTimeout(() => {}, 2000);
        }
      );

原文参考链接 https://blog.csdn.net/zuorish…

正文完
 0