以下是依赖于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"><imgsrc="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有变化以后 说明新图片已经生成 隐藏DOMthis.$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转blobbase64ToBlob(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);});