网页div转换成图片导出——html2canvas

时间:2020-12-14 00:28:17
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<!--此网页演示了html2canvas网页截图下载 -->	
	<head>
		<!-- jquery库和html2canvas库 -->
		<script type="text/javascript" src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
		<script type="text/javascript" src="http://www.boolaw.com/tpl/default/js/jquery-1.8.3.min.js"></script>
		<title>html2canvas网页截图</title>
	
		<!--需要注意的是,这里一定要等待js库和网页加载完毕后再执行函数  -->
		<!-- html2canvas()中,第一个参数是要截图的Dom对象,第二个参数时渲染完成后回调的canvas对象。  -->		
		<script type="text/javascript">
			$(function(){	
				print();
			});
			function print(){	
				html2canvas( $("#canv") ,{  		
					onrendered: function(canvas){
						$('#down_button').attr( 'href' , canvas.toDataURL() ) ;
						$('#down_button').attr( 'download' , 'myjobdeer.png' ) ;
					}
				});
			}
		</script>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	</head>
	<body>
		<div id="canv">
		Cease to struggle and you cease to live.<br/>

		</div>
		<a type="button" id="down_button">download</a>
	
	</body>
</html>

以上为html2canvas的一个小demo,可以将id为canv的div转换成图片并下载。

实际操作中以上代码只能转换显示器分辨率大小的网页图片,对于高度超过屏幕分辨率高度的网页不能全部导出。

经过测试,在第二个参数中加入高度即可将指定高度的网页导出为图片,代码如下:

function print(){
		html2canvas( $("#canv") ,{  		
			onrendered: function(canvas){
				$('#down_button').attr( 'href' , canvas.toDataURL() ) ;
				$('#down_button').attr( 'download' , 'myjobdeer.png' ) ;
			},
		height:9000
		});
	}