1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > JS—— canvas 加载图片等比例缩放

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

时间:2023-01-27 07:51:30

相关推荐

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

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

<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);}}})}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。