一、html2canvas
Screenshots with JavaScript
官網地址:http://html2canvas.hertzen.com/
html2canvas 能夠實現在用戶瀏覽器端直接對整個或部分頁面進行截屏。這個html2canvas腳本將當頁面渲染成一個Canvas圖片,通過讀取DOM並將不同的樣式應用到這些元素上實現。·
它不需要來自服務器任何渲染,整張圖片都是在客戶端瀏覽器創建。當瀏覽器不支持Canvas時,將採用Flashcanvas或ExplorerCanvas技術代替實現。以下瀏覽器能夠很好的支持該腳本:Firefox 3.5+, Google Chrome, Opera新的版本, IE9以上的瀏覽器。
html2canvas可以通過獲取HTML的某個元素,然後生成Canvas,能讓用戶保存爲圖片
使用案例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../plugins/html2canvas.min.js"></script>
</head>
<body>
<div id="capture" style="padding: 10px; background: #f5da55">
<h4 style="color: #000; ">Hello world!</h4>
<p>asdfasdfasdf</p>
<!-- <img src="http://yawz.qianlekh.com/file/logo/166.jpg"> -->
<p>這是一張跨域圖片</p>
<img src="http://p7.qhimg.com/t01ceede0272d4b5a8b.png" alt="來個跨區的圖片" style="width:50px;height:50px;">
</div>
<hr>
<script>
html2canvas(document.querySelector("#capture"),{
useCORS: true // 允許加載跨域圖片 ,同時需要對應服務器設置圖片跨域
}).then(canvas => {
document.body.appendChild(canvas)
});
</script>
</body>
</html>
展示結果:
二、滾動截屏
將目標區域Dom克隆,並設置克隆Dom的狂傲,截圖克隆區域即可
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
});
三、截屏區域有跨域圖片
// allowTaint: false 不允許跨域圖片污染畫布
// useCORS: true 允許加載跨域圖片
四、下載圖片
// 插入之前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)
});
更多: