前言
一旦有了女朋友,人很頹廢,加上換了工作,整整半年多未更新,懶得費解
前提:整個放canvas轉(zhuǎn)成圖片的區(qū)域
<div id="view">
</div>
坑1:滾動截屏
將目標區(qū)域Dom克隆,并設(shè)置克隆Dom的狂傲,截圖克隆區(qū)域即可
const targetDom = document.querySelector("#admin")
const copyDom = targetDom.cloneNode(true)
copyDom.style.width = targetDom.scrollWidth + 'px'
copyDom.style.height = targetDom.scrollHeight + 'px'
document.body.appendChild(copyDom)
html2canvas(copyDom, {
allowTaint: false,
useCORS: true,
height: targetDom.scrollHeight,
width: targetDom.scrollWidth
}).then(canvas => {
// canvas
});
坑2:截屏區(qū)域有跨域圖片
若是百度會發(fā)現(xiàn)修改源碼是最多的。其實那是老版本,新版本(1.x)只要配下參數(shù)即可即:
// allowTaint: false 不允許跨域圖片污染畫布
// useCORS: true 允許加載跨域圖片
坑3:下載圖片
移動端不好整,PC端就簡單了
// 插入之前canvas下
html2canvas(copyDom, {
allowTaint: false,
useCORS: true,
height: targetDom.scrollHeight,
width: targetDom.scrollWidth
}).then(canvas => {
this.printShow = true
copyDom.parentNode.removeChild(copyDom)
// console.log(canvas.style.width)
canvas.style.width = parseFloat(canvas.style.width) * 0.8 + 'px'
canvas.style.height = parseFloat(canvas.style.height) * 0.8 + 'px'
setTimeout(() => {
const container = document.querySelector('#view')
while (container.hasChildNodes()) {
container.removeChild(container.firstChild)
}
// toImage
const dataImg = new Image()
dataImg.src = canvas.toDataURL('image/png')
document.querySelector('#view').appendChild(dataImg)
const alink = document.createElement("a");
alink.href = dataImg.src;
alink.download = "testImg.jpg";
alink.click();
}, 0)
});