js 使用canvas 旋转 图片

拟墨画扇 提交于 2020-08-11 04:59:22

最左边是原始图片,中间是canvas内容,右边是将canvas内容导出到img标签中

 

canvas绘图时,确定图片的原始尺寸,不是显示的dom大小,需要创建元素后获得

如果使用dom大小的话,会在绘制时只能绘制出一部分

canvas目前的感觉是分为绘图层和展示层

旋转和移动的是绘图层的中心

展示层呈现内容,大小也是展示层的大小

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>Title</title>
		<style>
			.img {
				width: 300px;
				border: 1px solid black;
			}
		</style>
	</head>
	<body>
		<img class="img" id="source" src="./t.jpg" alt="" />
		<canvas class="img" id="rotationCanvas"></canvas>
		<img class="img" id="target" src="./t.jpg" alt="" />

		<button onclick="rotation()">旋转</button>
		<script>
			let degree = 0;
			const sourceImg = document.getElementById('source');
			const targetImg = document.getElementById('target');

			const rotationCanvas = document.getElementById('rotationCanvas');

			function getSize(url) {
				return new Promise((resolve) => {
					let img = document.createElement('img');
					img.onload = () => {
						resolve({
							width: img.width,
							height: img.height,
						});
					};

					img.src = url;
				});
			}

			async function rotation() {
				let d = (degree * Math.PI) / 180;
				degree += 30;
				console.log(d);
				let image = sourceImg;
				let size = await getSize(sourceImg.src);
				console.log('size', size);
				const canvasWidth = size.width;
				const canvasHeight = size.height;
				rotationCanvas.width = canvasHeight;
				rotationCanvas.height = canvasWidth;

				let surfaceContext = rotationCanvas.getContext('2d');
				surfaceContext.clearRect(0, 0, rotationCanvas.width, rotationCanvas.height);
				surfaceContext.save();
				// Translate to the center point of our image
				surfaceContext.translate(canvasHeight * 0.5, canvasWidth * 0.5);
				// Perform the rotation
				surfaceContext.rotate(d);
				// Translate back to the top left of our image
				// surfaceContext.translate(-image.width * 0.5, -image.height * 0.5);
				// Finally we draw the image
				// surfaceContext.drawImage(image, -image.width * 0.5, -image.height * 0.5);
				surfaceContext.drawImage(image, -canvasWidth / 2, -canvasHeight / 2);
				// surfaceContext.drawImage(image, canvasWidth/2, canvasHeight/2);
				// rotationCanvas.style.width = canvasHeight + 'px'
				// rotationCanvas.style.height = canvasWidth + 'px'
				surfaceContext.restore();
				// surfaceContext.scale(.5, .5)
				targetImg.src = rotationCanvas.toDataURL();
			}

			rotation();

			function getBase64(img) {
				console.log('img', img, canvasWidth, canvasHeight);
				canvas.width = canvasWidth;
				canvas.height = canvasHeight;
				ctx.drawImage(img, 0, 0, img.width, img.height);
				return canvas.toDataURL();
			}
		</script>
	</body>
</html>

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!