安装
npm install cropperjs
使用
<!-- 使用this.$refs.image获取element -->
<img ref="image" :src="fileObj.src">
<!-- 使用this.$refs.fileInput.click()上传图片 -->
<input ref="fileInput" type="file" name="file" multiple="multiple" @change="selectFile">
<el-button type="primary" @click="showFile">图片上传</el-button>
引入模块
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
data中的cropper配置项
options: {
viewMode: 1, // 0:无限制; 1:将裁剪框限制为不超过画布的大小, 2:限制最小画布尺寸以适应容器,如果画布和容器的比例不同,则最小画布将在其中一个维度中被额外的空格包围。, 3:限制最小画布尺寸以填充容器。如果画布和容器的比例不同,则容器将无法将整个画布适合其中一个尺寸。
dragMode: 'move', // 'crop':创建一个新的裁剪框 'move':移动画布 'none':do nothing
// aspectRatio: 16 / 9, // 设置裁剪框的宽高比。默认情况下,裁剪框是空闲比率。
data: {}, // 如果您已经存储了以前的裁剪数据,将在构建时自动传递给setData方法。
preview: '.small', // 添加额外的元素(容器)进行预览。
autoCropArea: 0.6, // 介于0和1之间的数字。定义自动裁剪区域大小(百分比)
checkCrossOrigin: true,
movable: true, // 启用移动图像。
rotatable: true, // 启用旋转图像。
scalable: true, // 启用缩放图像。
zoomable: true, // 启用缩放图像。
zoomOnTouch: true, // 启用通过拖动触摸缩放图像。
zoomOnWheel: true, // 启用通过滚动鼠标放大图像。。
cropBoxMovable: true, // 启用通过拖动来移动裁剪框。
cropBoxResizable: true, // 启用通过拖动调整裁剪框的大小。。
toggleDragModeOnDblclick: true, // 在裁剪器上点击两次时,启用“切割”和“移动”之间切换拖动模式。
// minContainerWidth: 700, // 容器的最小宽度。。
// maxContainerHeight: 500, // 容器的最小高度。。。
ready: function () {},
cropend: function () {},
crop: function () {}
},
创建一个新实例用于图像裁剪
mounted () {
this.myCropper = new Cropper(this.$refs.image, this.options)
},
打开文件选择框,选择文件
showFile () {
this.$refs.fileInput.click()
},
如果文件发生更改,就替换裁剪器中的图片
selectFile () {
const files = this.$refs.fileInput.files
if (files.length > 1) {
this.$message.warning('请选择一张图片')
} else if (files.length === 1) {
const blob = new Blob([files[0]])
const url = window.URL.createObjectURL(blob)
this.myCropper.replace(url, false)
}
},