利用SVG forginObject实现整个页面转成图片
复制可直接运行
注意:css中引入的背景图片未处理
var bodyE = document.querySelector('body')
domToImg(bodyE)
// 借助SVG forginObject 将DOM转为图片
function domToImg (dom) {
// 复制节点
var cloneDom = dom.cloneNode(true);
// cloneDom.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
var img = new Image();
img.onload = function () {
// 加载完
download(draw(img))
}
// 找到所有link
function getStyleAndLink () {
var styleArr = [];
var lks = document.querySelectorAll('link');
var styles = document.querySelectorAll('style');
if (styles.lenght > 0) {
for(var i = 0; i < styles.length; i++) {
styleArr.psuh(styles[0].innerText);
}
}
var promiseAll = [];
if (lks.length > 0) {
for(var i = 0; i < lks.length; i++) {
promiseAll.push( fetch(lks[i].href).then(response => {
return response.text();
}))
}
}
var p = Promise.all(promiseAll);
return new Promise((resolve, reject) => {
p.then(res => {
var newStyle = res.concat(styleArr).join('');
resolve(newStyle);
})
})
}
// 获取所有img 转成Base64
function getImg () {
var imgs = cloneDom.querySelectorAll('img');
for(var i = 0; i < imgs.length; i++) {
imgs[i].src = draw(imgs[i]).toDataURL();
}
}
getImg();
getStyleAndLink().then(res => {
var htmlSvg = `
data:image/svg+xml;charset=utf-8,
<svg xmlns="http://www.w3.org/2000/svg" width="${dom.offsetWidth}" height="${dom.offsetHeight}">
<foreignObject x="0" y="0" width="100%" height="100%">
${new XMLSerializer().serializeToString(cloneDom)}
<style>${res}</style>
</foreignObject>
</svg>
`;
console.log(htmlSvg)
htmlSvg = htmlSvg.replace(/\n/g, '').replace(/\t/g, '').replace(/#/g, '%23');
img.src = htmlSvg;
})
}
function draw (img) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
width = img.width,
height = img.height;
canvas.width = width;
canvas.height = height;
ctx.clearRect(0, 0, width, height);
ctx.drawImage(img, 0, 0);
return canvas;
}
function download (canvas) {
// 创建隐藏的可下载链接
var eleLink = document.createElement('a');
// 下载图片文件名就按照时间戳来
eleLink.download = 'zxx_png-' + (+new Date() + '').slice(1, 9) + '.png';
eleLink.style.display = 'none';
eleLink.href = canvas.toDataURL();
// 触发点击
document.body.appendChild(eleLink);
eleLink.click();
// 然后移除
document.body.removeChild(eleLink);
}