一、介绍
官网:http://html2canvas.hertzen.com/
二、引入
npm install html2canvas
import html2canvas from 'html2canvas';
或者直接下载 js 文件,引入
三、基本用法
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
});
四、长截图
/**
* @description 截图函数
* @params {...Array}
* 1、DomObj: 需要进行截图的Dom节点;
* 2、fileName: 截图命名;
* 3、ops: html2canvas配置项;
* 4、计算的截图宽度;
**/
function downloadImg(obj, fileName, ops = {}, width) {
return new Promise(resolve => {
setTimeout(() => {
// 复刻需要滚动截图的Dom, 要在改复制的Dom节点加滚动条, 否则会截图失败
let copyDom = null;
const copyOps = ops;
// 检查宽度是否大于项目全屏宽度
let copyWidth = null;
let flag = false;
if (width < 1803) {
copyWidth = 1803;
flag = false;
} else {
copyWidth = width;
flag = true;
copyDom = obj.cloneNode(true);
copyDom.style.width = `${copyWidth + 50}px`;
copyDom.style.height = `${obj.scrollHeight + 50}px`;
// 设置配置项 1、scale: 浏览器缩放值;2、width: 图片宽度;3、height: 图片高度; 4、x(scrollLeft) || y(scrollTop): 滚动轴的起始位置
copyOps.scale = window.devicePixelRatio;
copyOps.width = copyWidth + 50;
copyOps.height = obj.scrollHeight + 50;
copyDom.x = obj.scrollLeft;
// 设置ID为复刻Dom添加样式;
copyDom.id = 'copyDom';
// 将复刻元素插入HTML中
document.querySelector('body').appendChild(copyDom);
}
// 判断是否超过大小
html2canvas(flag ? copyDom : obj, copyOps).then(canvas => {
const saveUrl = canvas.toDateURL('image/png');
const aLink = document.createElement('a');
aLink.href = saveUrl;
aLink.download = fileName || '图片';
aLink.click();
if (flag) {
copyDom.parentNode.removeChild(copyDom);
}
aLink.parentNode.removeChild(aLink);
})
resolve('success');
}, 1)
})
}
五、canvas转图片
将canvas转化为图片并上传服务器,有两种思路
思路1 直接将canvas转化为base64编码,将base64编码的字符串上传服务器,让后端转化为图片;
思路2 需要将canvas的内容先转化为base64编码的字符串,再将字符串转化为file上传;
//canvas转化为64
canvasToBase64: function(canvas){
// 'image/png'可以换成'image/jpeg'
return canvas.toDataURL('image/png');
}
//canvas转化为图片
canvasToImg: function(canvas){
let image = new Image();
image.src = canvas.toDataURL('image/png')
return image;
}
//base64转化为file
base64ToFile: function(urlData, fileName){
let arr = urlData.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bytes = atob(arr[1]);
let n = bytes.length
let ia = new Uint8Array(n);
while (n--) {
ia[n] = bytes.charCodeAt(n);
}
return new File([ia], fileName, { type: mime });
}
axios上传canvas
//使用formData上传canvas
submitImg: function(canvas){
let param= new FormData();
param.append("file", this.base64ToFile(canvas.toDataURL('image/png')));
param.append("user_name", 'mason');
// 注意添加headers
axios.post('/que/admin/final/report/chess/image/add/', param, {headers:{'Content-Type': 'multipart/form-data'}}).then(res=>{
console.log(res.data);
});
}
ajax
let param= new FormData();
param.append("file", this.base64ToFile(canvas.toDataURL('image/png')));
param.append("user_name", 'mason');
$.ajax({
url: baseServer + '/actions/upload',
type: 'POST',
async: false,
data: param,
processData: false,
contentType: false,
beforeSend: function () {
},
success: function (data) {
console.log(data);
}
});