zoukankan      html  css  js  c++  java
  • 使用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 {
    			 800px;
    			height: auto;
    			margin: auto;
    		}
    
    		img {
    			 100%;
    		}
    
    		input {
    			 150px;
    			height: 30px;
    		}
    
    		button {
    			 60px;
    			height: 30px;
    			cursor: pointer;
    		}
    
    		.canvasbox canvas {
    			 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>
    
  • 相关阅读:
    css3线性渐变
    php的%s
    面向对象
    excel导入导出
    保存Excel
    保存word
    图片预览
    验证日期输入格式
    级联菜单
    中级前端知识点提要
  • 原文地址:https://www.cnblogs.com/yangxianyang/p/13675540.html
Copyright © 2011-2022 走看看