<script>var input = document.querySelector("input");var imgArr=[];input.addEventListener("input",function(){var files = this.files;var isOk= checkStyle(files);//如果为真 则上传图片不符合要求if(isOk){return;}//循环遍历 对图片进行压缩for(var i=0; i<files.length;i++){var imgUrl="";//定义一个初始的路径var fileReader=new FileReader();fileReader.readAsDataURL(files[i]);fileReader.addEventListener("load",function(){var img=new Image();img.src=this.result;img.addEventListener("load",function(){var widht=0;var height=0;if(img.width>img.height){var rate=img.width/img.height;height=500;img.height=img.height>height?height:img.height;img.width=img.height*rate;}else{var rate=img.height/img.width;width=500;img.widht=img.width>width?width:img.width;img.height=img.width*rate;}var canvas=document.createElement("canvas");canvas.width=img.width;canvas.height=img.height;var context=canvas.getContext("2d");//绘制图形context.drawImage(img,0,0,img.width,img.height);//生成一个data64格式的图片路径新的路径imgUrl=canvas.toDataURL("image/jpeg");imgArr.push(imgUrl);var imgBody=document.createElement("img");imgBody.src=imgUrl;document.body.appendChild(imgBody);})})}})//验证 文件格式function checkStyle(files){var reg= /\.(jpg|jpeg|png)$/;var isOk=false;for(var i=0; i<files.length;i++){if(!reg.test(files[i].name)){isOk=true;}}if(isOk){alert("图片格式不正确")}if(files.length>5||imgArr.length+files.length>5){alert("最多只能上传5张图")isOk=true;}return isOk;}</script>
如果觉得《利用canvas对图片进行等比例压缩》对你有帮助,请点赞、收藏,并留下你的观点哦!