项目中需要将图片进行等比例压缩展示,哎,烦!
HTML部分:
<input type="file" id="file">
js部分
let reader = new FileReader();
let imgFile = document.querySelector("#file");
imgFile.addEventListener('change', (e) => {
let file = e.target.files[0];
reader.readAsDataURL(file);
})
let img = new Image();
reader.onload = (e) => {
img.src = e.target.result;
}
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
img.onload = () => {
let originWidth = img.width;
let originHeight = img.height;
let maxWidth = 500;
let maxHeight = 400;
let targetWidth = originWidth;
let targetHeight = originHeight;
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
targetWidth = maxWidthl
targetHeight = Math.floor(maxWidth * (originHeight / originWidth))
} else {
targetWidth = Math.floor(maxHeight* (originWidth / originHeight))
targetHeight = maxHeight;
}
}
canvas.width = targetWidth;
canvas.height = targetHeight;
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(img, 0, 0, canvas.width, canvas.height);
let base64 = canvas.toDataURL('image/png');
console.log(base64) // 这个就是压缩后的链接
}