js截圖及繞過服務器圖片保存至本地(html2canvas)


  今天要分享的是用html2canvas根據自己的需求生成截圖,並且修復html2canvas截圖模糊,以及繞過服務器圖片保存至本地。  

  只需要短短的幾行代碼,就能根據所需的dom截圖,是不是很方便,但是生成的圖片模糊

//直接選擇要截圖的dom,就能截圖,但是因為canvas的原因,生成的圖片模糊
			html2canvas(document.querySelector('div')).then(function(canvas) {
            		document.body.appendChild(canvas);
      	 	 })

  

   常見的解決方案是,生成一個多倍的畫布,然后將其放在較小的容器內,這樣就解決了截屏模糊的尷尬。

 還有一個問題是怎么將圖片繞過服務器保存至本地,canvas有個toDataURL的方法,然后a標簽有個download屬性,感覺簡直天造之和。當然微信中屏蔽下載,可以借助微信的webview中的一個內置規則,只要是a標簽(不含href屬性)里面嵌套Img的,可以正常呼出保存至手機和分享給朋友的菜單欄。

以下是簡單的demo

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			*{
				margin: 0;
			}
			.test{
				width: 100px;
				height: 100px;
				text-align: center;
				line-height: 100px;
				background-color: #87CEEB;
				display: inline-block;
				vertical-align:top;
			}
			canvas{
				margin-right: 5px;
			}
			.down{
				float: right;
   				 margin: 40px 10px;
			}
		</style>
	</head>
	<body>
	<a class="down" href="" download="downImg">下載</a>
	
	<div class="test">測試</div>
	
	<script src="js/html2canvas.js"></script>
<script>
	//直接選擇要截圖的dom,就能截圖,但是因為canvas的原因,生成的圖片模糊
	html2canvas(document.querySelector('div')).then(function(canvas) {
    		document.body.appendChild(canvas);
 	 })
	//創建一個新的canvas
	var canvas2 = document.createElement("canvas");
	let _canvas = document.querySelector('div');
	var w = parseInt(window.getComputedStyle(_canvas).width);
	var h = parseInt(window.getComputedStyle(_canvas).height);
	//將canvas畫布放大若干倍,然后盛放在較小的容器內,就顯得不模糊了
	canvas2.width = w * 2;
	canvas2.height = h * 2;
	canvas2.style.width = w + "px";
	canvas2.style.height = h + "px";
	//可以按照自己的需求,對context的參數修改,translate指的是偏移量
	//	var context = canvas.getContext("2d");
	//	context.translate(0,0);
	var context = canvas2.getContext("2d");
	context.scale(2,2);
	 html2canvas(document.querySelector('div'),{canvas:canvas2}).then(function(canvas) {
    		document.body.appendChild(canvas);
    		//canvas轉換成url,然后利用a標簽的download屬性,直接下載,繞過上傳服務器再下載
    		document.querySelector(".down").setAttribute('href',canvas.toDataURL());
 	 });
</script>
	</body>
</html>

  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM