js实现裁剪
使用Canvas API实现图片裁剪
在JavaScript中,Canvas API提供了一种直接的方式来裁剪图片。通过创建一个<canvas>元素,可以绘制并裁剪图片的特定部分。
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
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');
使用HTML5的File API和Canvas
结合File API和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);
document.body.appendChild(canvas);
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
});
使用CSS的clip-path属性
对于简单的裁剪需求,CSS的clip-path属性也可以实现视觉效果上的裁剪。

const element = document.getElementById('image');
element.style.clipPath = 'polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%)';
注意事项
Canvas的drawImage方法参数较多,需要正确理解每个参数的含义。第三方库如cropper.js提供了更丰富的功能,但会增加项目体积。File API在处理大文件时可能需要考虑性能问题。CSS的clip-path虽然简单,但缺乏精确控制。






