js实现图片裁剪
使用Canvas API实现图片裁剪
Canvas API提供了一种简单的方式来实现图片裁剪功能。通过Canvas的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('image/png');
}
使用第三方库cropper.js
cropper.js是一个流行的图片裁剪库,提供丰富的配置选项和交互功能。
// 引入cropper.js库后
const image = document.getElementById('image');
const cropper = new Cropper(image, {
aspectRatio: 16 / 9,
crop(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/jpeg');
响应式图片裁剪实现
对于需要适应不同屏幕尺寸的图片裁剪,可以结合CSS和JavaScript实现响应式效果。
function responsiveCrop(imageElement, cropOptions) {
const imgWidth = imageElement.naturalWidth;
const imgHeight = imageElement.naturalHeight;
const scale = window.devicePixelRatio || 1;
const displayWidth = imageElement.clientWidth * scale;
const displayHeight = imageElement.clientHeight * scale;
const canvas = document.createElement('canvas');
canvas.width = cropOptions.width * scale;
canvas.height = cropOptions.height * scale;
const ctx = canvas.getContext('2d');
ctx.drawImage(
imageElement,
cropOptions.x * scale,
cropOptions.y * scale,
cropOptions.width * scale,
cropOptions.height * scale,
0,
0,
cropOptions.width * scale,
cropOptions.height * scale
);
return canvas.toDataURL('image/png');
}
实现圆形图片裁剪
通过Canvas的clip方法可以实现非矩形的裁剪效果,如圆形头像。
function cropCircle(image) {
const canvas = document.createElement('canvas');
const size = Math.min(image.width, image.height);
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(size/2, size/2, size/2, 0, Math.PI*2);
ctx.closePath();
ctx.clip();
ctx.drawImage(image,
(image.width-size)/2,
(image.height-size)/2,
size, size,
0, 0, size, size);
return canvas.toDataURL('image/png');
}
图片上传前客户端裁剪
在图片上传到服务器前进行客户端裁剪可以减少服务器负担。

function uploadCroppedImage(file, cropOptions) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = cropOptions.width;
canvas.height = cropOptions.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img,
cropOptions.x, cropOptions.y,
cropOptions.width, cropOptions.height,
0, 0, cropOptions.width, cropOptions.height);
canvas.toBlob(blob => {
const formData = new FormData();
formData.append('croppedImage', blob, 'cropped.jpg');
fetch('/upload', { method: 'POST', body: formData })
.then(res => resolve(res.json()))
.catch(err => reject(err));
}, 'image/jpeg', 0.9);
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
});
}






