dom-to-image實現的網頁截圖
阿新 • • 發佈:2018-11-01
dom-to-image如何使用請參考https://blog.csdn.net/u012260672/article/details/79302465
下面我們就不廢話了直接上演示:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>echarts 測試</title> <script type="text/javascript" src="dom-to-image.js"></script> </head> <body style="position:relative;"> <div style="width:100px;height:100px;background-color:#000;color:white;"> 尾氣請問氣味哦平均氣溫哦啤酒去i </div> <div style="width:100px;height:100px;background-color:#ccc;"></div> <div style="width:100px;height:100px;background-color:#666;color:#ccc;"> 請我陪考去請問哦 </div> <div style="width:100px;height:100px;background-color:#000;color:white;"> 尾氣請問氣味哦平均氣溫哦啤酒去i </div> <div style="width:100px;height:100px;background-color:#ccc;"></div> <div style="width:100px;height:100px;background-color:#000;color:white;"> 尾氣請問氣味哦平均氣溫哦啤酒去i </div> <div style="width:100px;height:100px;background-color:#ccc;"></div> <div style="width:100px;height:100px;background-color:#ddd;"></div> <div style="width:900px;height:100px;background-color:#666;"> 橋檔案額期望寄哦IQ叫我我就群毆我為奇偶去叫哦我IQ寄哦 </div> <div onclick="jt()">點選截圖</div> <script> var pointInfo= {}; document.onmousedown=function(e){ if(!pointInfo.bool)return; pointInfo.startInfo={ x:e.clientX+window.scrollX, y:e.clientY+window.scrollY }; pointInfo.eleArr[1].style.left=e.clientX+window.scrollX+"px"; pointInfo.eleArr[1].style.top=e.clientY+window.scrollY+"px"; } document.onmousemove=function(e){ if(!pointInfo.bool)return; if(!pointInfo.startInfo)return; pointInfo.eleArr[1].style.width=e.clientX-pointInfo.startInfo.x+window.scrollX+"px"; pointInfo.eleArr[1].style.height=e.clientY-pointInfo.startInfo.y+window.scrollY+"px"; } document.onmouseup=function(e){ if(!pointInfo.bool)return; if(!pointInfo.startInfo)return; pointInfo.bool=false; var c = document.createElement("canvas"); node=document.body; document.body.removeChild( pointInfo.eleArr[0]); var promise = domtoimage.toPng(node); promise.then(function(v){ var img =new Image(); img.src=v; c.width=parseInt(pointInfo.eleArr[1].style.width); c.height=parseInt(pointInfo.eleArr[1].style.height); var ctx = c.getContext("2d"); img.onload=function(){ ctx.drawImage(img,pointInfo.startInfo.x,pointInfo.startInfo.y,c.width,c.height,0,0,c.width,c.height); var imgS=document.createElement("img"); imgS.src=c.toDataURL(); document.body.appendChild(imgS); pointInfo.startInfo=null; } }); } function jt(){ var d= document.createElement("div"); var d2=document.createElement("div"); d.style.cssText="width:100%;height:100%;background-color:rgba(0,0,0,0.2);position:absolute;top:0;left:0;"; d2.style.cssText="position:absolute;background:rgba(255,255,255,0.2);"; pointInfo.eleArr= [d,d2]; pointInfo.bool=true; d.appendChild(d2); document.body.appendChild(d); } </script> </body> </html>
檢視效果的話請將domtoimage下載下來自己檢視
注意因為使用了toDataURL方法所以需要在伺服器下面才能看到效果請使用webstorm開啟檢視效果