js裁剪图片js实现
使用Canvas裁剪图片
Canvas API提供了drawImage方法,可以实现图片裁剪功能。该方法可以指定源图像的裁剪区域和目标画布的绘制位置及大小。
function cropImage(image, x, y, width, height) {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(image, x, y, width, height, 0, 0, width, height);
return canvas.toDataURL();
}
使用第三方库cropper.js
cropper.js是一个专业的图片裁剪库,提供了丰富的配置选项和交互功能。它支持拖拽、缩放、旋转等操作。
// 初始化cropper
const image = document.getElementById('image');
const cropper = new Cropper(image, {
aspectRatio: 16 / 9,
crop: function(event) {
console.log(event.detail.x, event.detail.y);
}
});
// 获取裁剪结果
const croppedCanvas = cropper.getCroppedCanvas();
const croppedImageUrl = croppedCanvas.toDataURL('image/jpeg');
响应式图片裁剪
对于需要适应不同屏幕尺寸的场景,可以使用CSS和JavaScript结合实现响应式裁剪。
function responsiveCrop(image, container) {
const containerWidth = container.offsetWidth;
const containerHeight = container.offsetHeight;
const imageAspect = image.naturalWidth / image.naturalHeight;
const containerAspect = containerWidth / containerHeight;
let cropWidth, cropHeight;
if (imageAspect > containerAspect) {
cropHeight = image.naturalHeight;
cropWidth = cropHeight * containerAspect;
} else {
cropWidth = image.naturalWidth;
cropHeight = cropWidth / containerAspect;
}
const x = (image.naturalWidth - cropWidth) / 2;
const y = (image.naturalHeight - cropHeight) / 2;
return cropImage(image, x, y, cropWidth, cropHeight);
}
上传前预览裁剪效果
在文件上传前实现客户端预览裁剪效果,可以提升用户体验。
const fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', function(e) {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
const cropped = cropImage(img, 0, 0, 300, 300);
document.getElementById('preview').src = cropped;
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
});
保存裁剪后的图片
将裁剪后的图片保存为文件或上传到服务器。
function saveCroppedImage(canvas, filename) {
canvas.toBlob(function(blob) {
const link = document.createElement('a');
link.download = filename;
link.href = URL.createObjectURL(blob);
link.click();
}, 'image/jpeg', 0.95);
}
性能优化建议
对于大尺寸图片,考虑先压缩再裁剪以提高性能。可以使用createImageBitmapAPI处理大图,它支持在Worker线程中处理图像。

async function processLargeImage(file) {
const bitmap = await createImageBitmap(file);
const canvas = new OffscreenCanvas(300, 300);
const ctx = canvas.getContext('2d');
ctx.drawImage(bitmap, 0, 0, 300, 300);
return canvas.convertToBlob();
}






