截屏

时间:2019-12-03
本文章向大家介绍截屏,主要包括截屏使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=Edge">
		<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
		<meta name="format-detection" content="telephone=no">
		<title></title>
		<!-- 移动端兼容css -->
		<link rel="stylesheet" href="css/mobile2.css">
		<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
		<style>
			* {
				margin: 0;
			}

			html {
				background: #fff;
				width: 100%;
				height: 100%;
			}

			.test {
				width: 100%;
				height: 3rem;
				text-align: center;
				line-height: 3rem;
				background-color: #fff;
				display: inline-block;
				vertical-align: top;
				color: red;
			}
			canvas {
				margin-right: 5px;
			}
			.down {
				float: left;
				margin: 40px 10px;
			}
			.mn{
				width:100%;
				height: auto;
				position: fixed;
				top:0;
				left: 0;
			}
		</style>
	</head>
	<body style="background: red;">
		<div class="test">测试</div>
		<div class="test">测试</div>
		<div class="test">测试</div>
		<div class="test">测试</div>
		<div class="test">测试</div>
		<div>
			<div class="down" id="down">生成图片</div>
		</div>
		<img class="mn" src="" id="imageId" alt="">
		<script>
			//创建一个新的canvas
			var canvas2 = document.createElement("canvas");
			let _canvas = document.querySelector('html');
			//此处可换body,或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('html'), {
				canvas: canvas2
			}).then(function(canvas) {
				//此处html可换body,或div等
				//document.body.appendChild(canvas);
				//canvas转换成url,然后利用a标签的download属性,直接下载,绕过上传服务器再下载
				// document.querySelector(".down").setAttribute('href', canvas.toDataURL());
				// $('.mn').attr("src",canvas.toDataURL());
				
				// 獲取到圖片路徑
				console.log(canvas.toDataURL());
				
				var btn = document.getElementById('down');
				btn.addEventListener('click', showMsg, false); 
				function showMsg() {
					document.getElementById("imageId").src = canvas.toDataURL();
				}
			});
		</script>
	</body>
	
</html>

  参考链接:

原文地址:https://www.cnblogs.com/pengxiangchong/p/11978104.html