1.安装html2canvas
npm install html2canvas
2.在需要生成海报的页面引入
import html2canvas from 'html2canvas';
html
//存放生成的图片
<div class="post" style="backgroundsize: 100%">
<img id="post" src="#" />
</div>
//要转化为图片的dom结构
<div class="bg-maskBox" ref="postContainer">
//不能用background-image 改成img标签装背景图
</div>
js方法
方法一
// html转换为img图片
htmlToimg() {
let dom = document.getElementsByClassName("bg-maskBox")[0];
let width = dom.offsetWidth;
let height = dom.offsetHeight;
let canvas = document.createElement("canvas");
let scale = 2; //数值大一点也可以,就是会影响生成图片的速度
//画布实际宽度和高度
canvas.width = width * scale;
canvas.height = height * scale;
// 浏览器中被渲染的高度和宽度
canvas.style.width = width * scale + "px";
canvas.style.height = height * scale + "px";
canvas.getContext("2d");
let opts = {
useCORS: true,
//backgroundColor: "transparent", //去掉白边
backgroundColor:"rgba(255, 255, 255, 0)",//背景透明
scrollX: 0,
scrollY: 0,
scale: scale,
canvas: canvas,
dpi: window.devicePixelRatio,
};
html2canvas(dom, opts).then((canvas) => {
canvas.toBlob((blob) => {
var imgUrl = canvas.toDataURL("image/png", 1); // 获取生成的图片的url
// let newImg = document.createElement("img");
// newImg.src = imgUri;
// this.$refs.post.append(newImg);
document.getElementById("post").src = imgUrl;
});
});
},
htmlToimg()
方法二
// html转换为img图片
htmlToimg() {
let dom = document.getElementsByClassName('bg-maskBox')[0];
let scale = window.devicePixelRatio;
html2canvas(dom, {
useCORS: true,
allowTaint: false,
height: dom.offsetHeight, //画布高度
width: dom.offsetWidth, //画布宽度
scrollX: 0,
scrollY: 0,
// 页面下拉时会导致生成的图片整体偏移
// scrollX: -scrollX,
// scrollY: -scrollY,
dpi: window.devicePixelRatio ,
scale: scale,
backgroundColor: null, //去掉白边
}).then((canvas) => {
canvas.toBlob((blob) => {
var imgUrl = canvas.toDataURL("image/png", 1); // 获取生成的图片的url
document.getElementById("post").src = imgUrl;
});
});
},
htmlToimg()
踩坑之路
[ 图片模糊问题解决方法 ]
- 确认要被截屏的dom结构中是否有background-image形式的图片,如果有则需要改成img标签,否则截图会模糊
- 修改canvas画布的scale和dpi属性
[ 图片可以生成但无法在网页单独打开或保存在手机 ]
调整scale参数值,在保证图片清晰度的前提下,减小scale值