使用canvas把照片旋转任意角度

1. 效果

演示地址:https://www.albertyy.com/2020/8/rotateImg.html

2. canvas

关于canvas的使用我在这篇文章 https://blog.csdn.net/qq_23853743/article/details/107434946 中有简单的介绍,可以看一下。

3. 代码实现

<!DOCTYPE html>
<html>
	<head>
		<title>图片旋转:公众号AlbertYang</title>
	</head>
	<style type="text/css">
		#content {
			width: 800px;
			height: auto;
			margin: auto;
		}

		img {
			width: 100%;
		}

		input {
			width: 150px;
			height: 30px;
		}

		button {
			width: 60px;
			height: 30px;
			cursor: pointer;
		}

		.canvasbox canvas {
			width: 100%
		}
	</style>

	<body>
		<div id="content">
			<div class="imgbox"><img id="img" src="./img/image_20200813.jpg"></div>
			<div>
				<input type="number" id="number" name="" placeholder="输入旋转角度">
				<button onclick="drawImg()">draw</button>
			</div>
			<div class="canvasbox" width="800px">
				<img id="testimg" />
			</div>
		</div>
	</body>
	<script type="text/javascript">
		function drawImgToCanvas(image, rotate) {
			var testImg = document.getElementById('testimg')
			var canvas = document.createElement("canvas");
			var context = canvas.getContext('2d')
			var img = new Image();
			console.log(60);
			img.setAttribute('crossOrigin', 'Anonymous')
			img.src = image.src;

			img.onload = function() {
				canvas.width = img.height;
				canvas.height = img.width;

				context.translate(canvas.width / 2, canvas.height / 2)
				context.rotate(rotate * Math.PI / 180)
				context.translate(-canvas.width / 2, -canvas.height / 2)
				context.drawImage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.height / 2)
				context.translate(canvas.width / 2, canvas.height / 2)
				context.rotate(-rotate * Math.PI / 180)
				context.translate(-canvas.width / 2, -canvas.height / 2)
				context.restore()
				var base64 = canvas.toDataURL("image/jpeg", 0.9);
				testImg.src = base64;
				console.log('base64', base64);
			};


		}

		function drawImg() {
			var image = document.getElementById('img');
			var rotate = document.getElementById('number').value * 1;

			drawImgToCanvas(image, rotate);
		}
	</script>
</html>

 

©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页