js裁剪图片js实现
使用Canvas API裁剪图片
Canvas API提供了一种简单的方式来裁剪和操作图片。通过创建一个canvas元素,可以将图片绘制到画布上并裁剪指定区域。
function cropImage(imageSrc, x, y, width, height) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = function() {
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, x, y, width, height, 0, 0, width, height);
const croppedImageUrl = canvas.toDataURL('image/png');
console.log(croppedImageUrl); // 输出裁剪后的图片URL
};
img.src = imageSrc;
}
使用第三方库cropper.js
cropper.js是一个功能强大的图片裁剪库,支持拖拽、缩放和旋转等功能。安装后可以通过简单配置实现复杂的裁剪功能。

import Cropper from 'cropperjs';
const image = document.getElementById('image');
const cropper = new Cropper(image, {
aspectRatio: 16 / 9,
crop: function(event) {
console.log(event.detail.x);
console.log(event.detail.y);
console.log(event.detail.width);
console.log(event.detail.height);
}
});
// 获取裁剪后的图片数据
const croppedCanvas = cropper.getCroppedCanvas();
const croppedImageUrl = croppedCanvas.toDataURL('image/png');
使用HTML5的File API处理上传图片
结合File API和Canvas,可以实现上传图片后立即裁剪的功能。用户选择文件后,通过FileReader读取图片并在Canvas上处理。

document.getElementById('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 canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 200;
canvas.height = 200;
ctx.drawImage(img, 50, 50, 200, 200, 0, 0, 200, 200);
const croppedUrl = canvas.toDataURL('image/jpeg');
document.getElementById('preview').src = croppedUrl;
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
});
响应式图片裁剪
为了实现响应式裁剪,可以根据屏幕尺寸动态调整裁剪区域。使用窗口 resize 事件监听器,在窗口大小变化时重新计算裁剪尺寸。
window.addEventListener('resize', function() {
const screenWidth = window.innerWidth;
const cropWidth = screenWidth > 768 ? 300 : 150;
const cropHeight = screenWidth > 768 ? 300 : 150;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = cropWidth;
canvas.height = cropHeight;
ctx.drawImage(img, 0, 0, cropWidth, cropHeight);
});
保存裁剪后的图片
裁剪完成后,通常需要将图片保存或上传到服务器。可以通过将Canvas转换为Blob对象来实现。
canvas.toBlob(function(blob) {
const formData = new FormData();
formData.append('croppedImage', blob, 'cropped-image.png');
fetch('/upload', {
method: 'POST',
body: formData
});
}, 'image/png');






