js裁剪图片js实现
使用Canvas实现图片裁剪
在JavaScript中,Canvas API提供了一种简单而强大的方式来裁剪图片。以下是一个基本的实现方法:
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
function cropImage(image, x, y, width, height) {
canvas.width = width;
canvas.height = height;
ctx.drawImage(image, x, y, width, height, 0, 0, width, height);
return canvas.toDataURL('image/png');
}
使用第三方库实现更复杂的裁剪
对于更高级的裁剪需求,可以使用专门的库如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');
实现圆形头像裁剪
对于圆形头像裁剪,可以使用Canvas的clip方法:

function cropCircle(image, size) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = size;
canvas.height = size;
ctx.beginPath();
ctx.arc(size/2, size/2, size/2, 0, Math.PI*2);
ctx.closePath();
ctx.clip();
ctx.drawImage(image, 0, 0, size, size);
return canvas.toDataURL('image/png');
}
响应式图片裁剪
在响应式设计中,需要考虑图片的缩放比例:
function responsiveCrop(image, cropArea, displaySize) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 计算实际裁剪比例
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
canvas.width = displaySize.width;
canvas.height = displaySize.height;
ctx.drawImage(
image,
cropArea.x * scaleX,
cropArea.y * scaleY,
cropArea.width * scaleX,
cropArea.height * scaleY,
0,
0,
displaySize.width,
displaySize.height
);
return canvas.toDataURL('image/jpeg');
}
保存裁剪后的图片
将裁剪后的图片保存为文件:
function saveCroppedImage(dataUrl, fileName) {
const link = document.createElement('a');
link.download = fileName;
link.href = dataUrl;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}






