在JavaScript中,改变图片大小通常涉及到两个步骤:加载图片并调整其尺寸,然后将调整后的图片绘制到一个新的<canvas>
元素上。以下是一个详细的步骤和示例代码:
CanvasRenderingContext2D
对象的方法,用于在画布上绘制图像。以下是一个简单的示例,展示如何使用JavaScript改变图片大小:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Resize Image</title>
</head>
<body>
<input type="file" id="imageUpload" accept="image/*">
<canvas id="resizedCanvas" style="display: none;"></canvas>
<img id="resizedImage" alt="Resized Image">
<script>
document.getElementById('imageUpload').addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const img = new Image();
img.onload = function() {
const canvas = document.getElementById('resizedCanvas');
const ctx = canvas.getContext('2d');
const maxWidth = 300; // 设置最大宽度
const maxHeight = 300; // 设置最大高度
let width = img.width;
let height = img.height;
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
const resizedImage = document.getElementById('resizedImage');
resizedImage.src = canvas.toDataURL('image/jpeg');
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
});
</script>
</body>
</html>
FileReader
读取文件内容。Image
对象并设置其src
属性为读取到的数据URL。drawImage
方法将调整后的图片绘制到<canvas>
上。<canvas>
的内容转换为数据URL,并设置为<img>
标签的src
属性。canvas.toDataURL
时,可以调整质量参数(如'image/jpeg', 0.9
)以平衡文件大小和质量。通过这种方式,你可以在客户端有效地处理和显示不同大小的图片。
领取专属 10元无门槛券
手把手带您无忧上云