文档地址:https://html2canvas.hertzen.com/
安装:
npm install --save html2canvas
或者
yarn add html2canvas
使用:
html2canvas(document.getElementById('screenshot'), {
// 配置参数 文档:[https://html2canvas.hertzen.com/configuration](https://html2canvas.hertzen.com/configuration)
}).then((canvas) => {
// 创建图片容器
var imgElement = new Image();
imgElement.src = canvas.toDataURL();
console.log(canvas.toDataURL());
});
问题汇总
-
html2canvas 转换包含具有input框页面时,input框内文字不垂直居中:
版本换成1.0.0!使用1.4.1版本就出现这种情况; -
如果截取的节点是长图,页面向下滑动时截取页面不全:
(1)滚动条置顶,截图开始前先置顶滚动条,截取完成后再恢复滚动条。1.0.0版本适用// 置顶滚动条 let oldScrollTop = window.scrollY || document.body.scrollTop; document.documentElement.scrollTop = document.body.scrollTop = 0; // 设置滚动条原来位置 document.documentElement.scrollTop = document.body.scrollTop = oldScrollTop;
(2)添加配置参数。1.0.0版本无效
html2canvas(document.getElementById('screenshot'), { height: document.getElementById('screenshot').scrollHeight, windowHeight: document.getElementById('screenshot').scrollHeight }).then(canvas => { //在此处拿到tempImg.src就是生成的base64图片,再进行后续业务逻辑处理 })
-
只截取当前窗口页面:
在长节点外层包裹一层盒子设置盒子属性:`
width: 100%;
height: 100%;
overflow: auto;
将盒子设为截取DOM对象