1,html2canvas版本为 0.5.0-beta4
2,配合Canvas2Image.js
//保存图片(注意html2Canvas版本的问题 可能出现截图只显示一半 当前版本html2canvas 0.5.0-beta4)
import html2canvas from "../../asset/html2canvas.min.js";
import Canvas2Image from "../../asset/canvas2image.js";
//执行截图
html2Canvas() {
//需要截图的包裹的(原生的)DOM 对象
let shareContent = document.getElementById("posterImg");
let width = shareContent.offsetWidth; //获取dom 宽度
let height = shareContent.offsetHeight; //获取dom 高度
let canvas = document.createElement("canvas"); //创建一个canvas节点
let context = canvas.getContext('2d');
let scale = 2; //解决高清屏图片模糊
canvas.width = width * scale; //定义canvas 宽度 * 缩放
canvas.height = height * scale; //定义canvas高度 *缩放
// 获取元素相对于视窗的偏移量
canvas.style.width = width * scale + "px";
canvas.style.height = height * scale + "px";
canvas.getContext("2d").scale(scale, scale); //获取context,设置scale
let rect = $("#posterImg").get(0).getBoundingClientRect();
// 设置context位置, 值为相对于视窗的偏移量的负值, 实现图片复位
context.translate(-rect.left, -rect.top);
let opts = {
scale: scale, // 添加的scale 参数
canvas: canvas, //自定义 canvas
logging: false, //日志开关,便于查看html2canvas的内部执行流程
width: width, //dom 原始宽度
height: height, //dom 原始高度
useCORS: true // 【重要】开启跨域配置
};
html2canvas(shareContent, opts).then(function(canvas) {
// 【重要】关闭抗锯齿
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
//生成图片
let img = Canvas2Image.convertToImage(canvas, canvas.width, canvas.height);
coursemanage.downloadPoster(img.src);
});
},