当前位置: 首页 > 工具软件 > canvas.js > 使用案例 >

插件 html2canvas.js和canvas2image.js实现 截图 长按保存至相册 功能

莫振
2023-12-01

插件下载:
html2canvas.js
canvas2image.js

Demo代码:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
		<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
		<meta name="viewport" content="width=750 user-scalable=no" />
		<style>
			html,
			body {
				width: 100%;
				height: 100%;
				margin: 0;
			}			
			.wrapper {
				width: 100%;
				height: 100%;
				margin: 0;
				max-width: 750px;
				display: flex;
				flex-flow: column nowrap;
				justify-content: center;
				align-items: center;
				overflow: hidden;
			}
			
			.imgbox {
				width: 80%;
				height: auto;
				text-align: center;
			}
			img{
				width: 100%;
			}
			p{
				font-size: 30px;
			}
		</style>
	</head>

	<body>
		<div class="wrapper">
			<div class="imgbox" id="savecont">
				<img id='imgInit' src="img/myimg.png" />
				<p>我是保存图片的提示文字</p>
			</div>
		</div>
		<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
		<script type="text/javascript" src="js/html2canvas.min.js"></script>
		<script type="text/javascript" src="js/canvas2image.js"></script>
		<script>
			$(function(){
				cut_pic('savecont');
			});
			//截图
			function cut_pic(cid) {
				const shareContent = document.getElementById(cid);
				const width = shareContent.offsetWidth;
				const height = shareContent.offsetHeight;
				const canvas = document.createElement("canvas");
				const scale = 2;

				canvas.width = width * scale;
				canvas.height = height * scale;
				canvas.getContext("2d").scale(scale, scale);

				const opts = {
					scale: scale,
					canvas: canvas,
					logging: true,
					width: width,
					height: height,
					useCORS: true
				};

				html2canvas(shareContent, opts).then(function(canvas) {
					const context = canvas.getContext("2d");

					context.mozImageSmoothingEnabled = false;
					context.webkitImageSmoothingEnabled = false;
					context.msImageSmoothingEnabled = false;
					context.imageSmoothingEnabled = false;

					const img = Canvas2Image.convertToImage(canvas, canvas.width, canvas.height);
					const t = "#" + cid

					$(t).html(img);

					$(img).css({
						"width": canvas.width / 2 + "px",
						"height": canvas.height / 2 + "px",
					});

				});
			}
		</script>
	
	</body>

</html>
 类似资料: