vue 实现图片截取
使用 Vue 实现图片截取
在 Vue 中实现图片截取功能通常需要借助第三方库或原生 Canvas API。以下是两种常见的方法:
使用 cropperjs 库
安装 cropperjs 库:
npm install cropperjs
在 Vue 组件中使用:

<template>
<div>
<img ref="image" src="your-image-source.jpg" alt="Image to crop">
<button @click="cropImage">Crop</button>
</div>
</template>
<script>
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';
export default {
mounted() {
this.cropper = new Cropper(this.$refs.image, {
aspectRatio: 16 / 9,
viewMode: 1,
});
},
methods: {
cropImage() {
const canvas = this.cropper.getCroppedCanvas();
const croppedImage = canvas.toDataURL('image/jpeg');
// 使用 croppedImage,可以显示或上传
}
},
beforeDestroy() {
this.cropper.destroy();
}
};
</script>
使用原生 Canvas API
<template>
<div>
<input type="file" @change="loadImage" accept="image/*">
<canvas ref="canvas"></canvas>
<button @click="crop">Crop</button>
</div>
</template>
<script>
export default {
data() {
return {
image: null,
ctx: null,
startX: 0,
startY: 0,
endX: 0,
endY: 0,
isDragging: false
};
},
mounted() {
this.ctx = this.$refs.canvas.getContext('2d');
},
methods: {
loadImage(e) {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = (event) => {
this.image = new Image();
this.image.onload = () => {
this.$refs.canvas.width = this.image.width;
this.$refs.canvas.height = this.image.height;
this.ctx.drawImage(this.image, 0, 0);
};
this.image.src = event.target.result;
};
reader.readAsDataURL(file);
},
crop() {
const width = this.endX - this.startX;
const height = this.endY - this.startY;
const data = this.ctx.getImageData(this.startX, this.startY, width, height);
this.$refs.canvas.width = width;
this.$refs.canvas.height = height;
this.ctx.putImageData(data, 0, 0);
}
}
};
</script>
实现拖拽选择区域功能
为上述 Canvas 方案添加鼠标事件处理:
// 在 mounted 中添加事件监听
this.$refs.canvas.addEventListener('mousedown', this.startSelection);
this.$refs.canvas.addEventListener('mousemove', this.drawSelection);
this.$refs.canvas.addEventListener('mouseup', this.endSelection);
// 添加方法
methods: {
startSelection(e) {
this.isDragging = true;
this.startX = e.offsetX;
this.startY = e.offsetY;
this.endX = e.offsetX;
this.endY = e.offsetY;
},
drawSelection(e) {
if (!this.isDragging) return;
this.endX = e.offsetX;
this.endY = e.offsetY;
// 清除并重绘
this.ctx.clearRect(0, 0, this.$refs.canvas.width, this.$refs.canvas.height);
this.ctx.drawImage(this.image, 0, 0);
// 绘制选择框
this.ctx.strokeStyle = 'red';
this.ctx.lineWidth = 2;
this.ctx.strokeRect(
this.startX,
this.startY,
this.endX - this.startX,
this.endY - this.startY
);
},
endSelection() {
this.isDragging = false;
}
}
注意事项
-
对于生产环境,推荐使用成熟的库如 cropperjs 或 vue-cropper,它们提供了更丰富的功能和更好的用户体验。

-
移动端支持需要考虑触摸事件,cropperjs 已经内置了触摸支持。
-
图片上传前考虑压缩处理,特别是移动设备拍摄的大尺寸图片。
-
跨域问题:如果处理来自不同域的图片,需要确保服务器设置了正确的 CORS 头,或者将图片代理到同域。






