JS—— canvas 加载图片等比例缩放

版权声明:文章资料来源于网络,都是由作者自己总结下来以供参考学习~如涉及版权问题请联系作者! https://blog.csdn.net/C_hydar/article/details/86299583

第一种:等比例缩放图片(没有设置清除画布,所以在第一次上传图片后再上传一次会被覆盖掉)

<input type="file" name="" id="inputBox">	<!-- 获取对文件的描述信息 -> 选择文件 -->
<canvas id="avatar"></canvas>   <!-- 在画布上加载图片 -->

<script type="text/javascript">
	window.onload = function(){
		var canvas = document.getElementById('avatar');
		// 检测canvas支持性
		if (canvas.getContext) {
			var ctx = canvas.getContext('2d');	// 返回一个对象,该对象提供了用在画布上绘图的方法和属性
		}else {
			document.write("你的浏览器不支持canvas,请升级你的浏览器");
			// return 
		}
		// canvas 大小
		canvas.width = document.documentElement.clientWidth;
		canvas.height = document.documentElement.clientHeight - 102;
		
		// 读取文件数据 -> 显示图片
		var inputBox = document.getElementById("inputBox");
		inputBox.addEventListener("change", function() {
			var reader = new FileReader();
			reader.readAsDataURL(inputBox.files[0]);  // 发起异步请求
			reader.onload = function() {
				// 图片加载完后,将其显示在canvas中
				var img = new Image();
				img.src = this.result;
				img.onload = function() {
					// 等比例缩放图片
					var scale = 1;
					var tt = 1000; // 可以根据具体的要求去设定
					if (this.width > tt || this.height > tt) {
						if (this.width > this.height) {
							scale = tt / this.width;
						}else {
							scale = tt / this.height;
						}
					}
					ctx.width = this.width * scale;
					ctx.height = this.height * scale; // 计算等比缩小后图片

					ctx.drawImage(this, 0, 0, ctx.width, ctx.height);  // 加载图片
				}
			}
		})
	}
</script>

第二种:上传的图片的宽/高会等比例满屏 (设置了清除画布,所以第二次上传图片不会覆盖第一次上传的图片)

有一个问题就是像素小的图片会放在角落上,这时候要设置在画布居中显示。还有一个问题就是,像素小的图片放大了会模糊。

read(ctx,canvas.width,canvas.height);
// 读取文件的数据
	function read(ctx,canvasWidth, canvasHeight) {
		var inputBox = document.getElementById("inputBox");
		inputBox.addEventListener("change", function() {
			console.log('清除画布');
			ctx.clearRect(0,0,canvasWidth,canvasHeight);
			var reader = new FileReader();
			reader.readAsDataURL(inputBox.files[0]);  // 发起异步请求
			reader.onload = function() {
				// 读取完成后,数据保存在对象的result 属性中
				// 图片加载完后,将其显示在canvas中
				var img = new Image();
				img.src = this.result;
				img.onload = function() {
					var xRate = canvasWidth / img.width;
					var yRate = canvasHeight / img.height;
					var setRate = xRate<yRate ? xRate : yRate;
					if(setRate>5){ setRate = 5;}
					ctx.drawImage(this, 0, 0, img.width * setRate, img.height*setRate);
				}
			}
		})
	}

猜你喜欢

转载自blog.csdn.net/C_hydar/article/details/86299583