记录使用html2canvas,生成海报
原理:使用canvas绘画DOM,转成图片
html2canvas:html2canvas
引入:html2canvas.min.js
1、使用dom把你要生成的海报组装好,如果当用户点击的时候在去展示海报的话,可以吧海报定位到 z-index:-1; 不要使用隐藏(如果隐藏的话是无法生成海报的)
2、上代码
var copyDom = $('.Posters')[0]; //海报dom
var width = copyDom.offsetWidth;
var height = copyDom.offsetHeight;
var canvas = document.createElement("canvas");
//这里为了让图片清晰放大了6倍
var scale = 6; //放大四倍,让图片变的高清
canvas.width = width * scale;
canvas.height = height * scale;
canvas.getContext("2d").scale(scale, scale);
var opts = {
scale: scale,
canvas: canvas,
width: width,
height: height
};
html2canvas(copyDom, opts).then(canvas => {
//canvas转base64
let dataURL = canvas.toDataURL("image/png");
$('.PostersImg img').attr('src', dataURL);
//layer弹出框
layer.open({
type: 1,
shadeClose: true,
closeBtn: false,
title: '',
area: ['80%'],
content: $('.PostersImg'),
})
});
3、展示