以下是依賴於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);
}
);