<!DOCTYPE html>
<html>
<head>
<title>JS 按比例缩小图片宽高</title>
</head>
<body>
<div>
<input type="file" name="" id="upload">
<img src="" alt="" id="preview">
</div>
</body>
<script>
var upd =document.getElementById('upload');
upd.addEventListener('change',function(e){
var file=e.target.files[0];
var reader=new FileReader();
var img = document.createElement('img');
var canvas=document.createElement('canvas');
var context=canvas.getContext('2d');
reader.onload=function(e){
img.src = e.target.result;
img.onload = function () {
var imgWidth=this.width;//上传图片的宽
var imgHeight = this.height;//上传图片的高
//按比例缩放后图片宽高
var targetWidth = imgWidth;
var targetHeight = imgHeight;
var maxWidth=1920;//图片最大宽
var maxHeight = 1080;//图片最大高
var scale = imgWidth / imgHeight;//原图宽高比例
//如果原图宽大于最大宽度
if(imgWidth>maxWidth){
targetWidth = maxWidth;
targetHeight = targetWidth/scale;
}
//缩放后高度仍然大于最大高度继续按比例缩小
if(targetHeight>maxHeight){
targetHeight = maxHeight
targetWidth = targetHeight*scale;
}
canvas.width=targetWidth;//canvas的宽=图片的宽
canvas.height=targetHeight;//canvas的高=图片的高
context.clearRect(0,0,targetWidth,targetHeight)//清理canvas
context.drawImage(img,0,0,targetWidth,targetHeight)//canvas绘图
var newUrl=canvas.toDataURL('image',0.92);//canvas导出成为base64
preview.src=newUrl
}
}
reader.readAsDataURL(file);
})
</script>
</html>