引入:
官网:https://www.npmjs.com/package/vue-cropperjs
控制台输入:
npm install --save vue-cropperjs
vue 项目中引入:
import Cropper from 'cropperjs' let projectEditVue = new Vue({ el: '#detailEdit', delimiters: ['{[', ']}'], components: { Cropper, }, data () { return {} } }) Vue.use({ projectEditVue, })
初始化裁剪框:
html:
js:
mounted () { // 初始化裁剪框 var image = document.getElementById('image') this.cropper = new Cropper(image, { guides: false, // 是否在剪裁框上显示虚线 aspectRatio: 420 / 213, // 设置剪裁容器的比例 minContainerHeight: 319.5, minContainerWidth: 630, dragMode: 'move', // 移动 canvas zoomOnWheel: true, // 是否允许通过鼠标滚轮来缩放图片 background: true, // 是否在容器上显示网格背景 rotatable: true, // 是否允许旋转图片 ready () { this.cropper.crop() }, }) },
上传图片:
confirm () {
let vm = this
vm.cropper.getCroppedCanvas({
420,
height: 213,
fillColor: '#fff',
imageSmoothingEnabled: false,
imageSmoothingQuality: 'high',
}).toBlob(function (blob) {
let croppedImage = new File([blob], vm.logoName, { lastModified: Date.now() })
api.media.uploadImageTo('project_logo')({
file: croppedImage,
}).then((response) => {
if (response.status === 200) {
let res = response.data.data[0]
vm.cropper.replace(res.download_url)
}
})
})
},
下面说下放大缩小左右旋转的裁剪工具:
根据 html 那张图可见,给四个工具图片绑定四个事件,分别是:zoomIn zoomOut rotateLeft rotateRight, 对应的方法写法为:
zoomIn () { this.cropper.zoom(-0.1) }, zoomOut () { this.cropper.zoom(0.1) }, rotateLeft () { this.cropper.rotate(-90) }, rotateRight () { this.cropper.rotate(90) },