html2canvas:将dom转换为画布
Posted 码工思博
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html2canvas:将dom转换为画布相关的知识,希望对你有一定的参考价值。
以下是依赖于html2canvas生成的海报效果,亲测有效
以一张背景图+二维码的布局为例
html部分:
<div class="container">
<div class="share-img">
<img style="width: 300px; height: 300px" :src="imgUrl" />
</div>
<div class="creat-img" ref="box">
<img
src="https://img0.baidu.com/it/u=3998012246,2453684564&fm=26&fmt=auto&gp=0.jpg"
/>
<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...
以上是关于html2canvas:将dom转换为画布的主要内容,如果未能解决你的问题,请参考以下文章
html2canvas ,将渲染画布保存为 gif 而不是 png?