一、首先安装插件
npm/cnpm install cropperjs
二、引入插件:
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.min.css'
三、编写页面代码:
//左边按钮
<div class="rc-cropper__iconCrop1">
<el-tooltip content="裁剪" placement="right">
<el-button type="primary" icon="el-icon-plus" size="small" @click="initCropper()" :disabled="croppShow">裁剪</el-button>
</el-tooltip>
</div>
<div style="display: flex;margin-top: 10px;">
<el-tooltip content="确认裁剪" placement="right" v-if="cropper">
<el-button type="success" size="mini" @click="sureCropper()"><i class="el-icon-check"></i></el-button>
</el-tooltip>
<el-tooltip content="取消裁剪" placement="right" v-if="cropper">
<el-button type="danger" size="small" @click="cancelCropper()" v-if="cropper"><i class="el-icon-close"></i></el-button>
</el-tooltip>
</div>
//中间主要部分
<div class="div_main">
<canvas :id="url" ref="canvas" style="width: 100%;height: 100%;"> </canvas>
</div>
//右边显示截图完成的图片
<div style="width:9%;height:100%;float: right;border: 1px deepskyblue solid;">
<div v-for="item in cropImg" style="margin: 0 auto;width: 72px;height: 72px;margin-top: 50px;margin-bottom: 1px;">
<el-image :src="item.imgUrl" :preview-src-list="srcList" style="width: 70px;height: 70px;"></el-image>
<span style="text-align: center;">{{item.index}}</span>
</div>
</div>
四、变量定义:
data () {
return {
cropImg:[], //截图数组
cropper: null,
croppShow: false,
index:0, //截图下标
srcList:[] //点击放大预览数组
}
},
五、js代码:
mounted(){
this.drawImg()
},
methods: {
// 在canvas上绘制图片
drawImg (href) {
this.$nextTick(() => {
let canvas = document.getElementById(this.url)
if (canvas) {
canvas.width = 720
canvas.height = 480
let ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, canvas.width, canvas.height)
let img = new Image()
img.crossOrigin = 'Anonymous'
img.src = href || this.url
img.onload = function () {
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
}
}
})
},
// 显示裁剪框
initCropper () {
this.drawImg()
this.croppShow = true
let cropper = new Cropper(this.$refs.canvas, {
checkCrossOrigin: true,
viewMode: 2,
aspectRatio: 3 / 2
})
this.cropper = cropper
},
// 确认裁剪
sureCropper () {
let _this = this
_this.cropper.getCroppedCanvas().toBlob(function (blob) {
const href = window.URL.createObjectURL(blob)
// _this.drawImg(href)
_this.index++ //下标
let dataurl={
imgUrl:href,
index:_this.index
}
_this.cropImg.push(dataurl) //把图片链接、下标push进截图数组
_this.srcList.push(href) //截图预览数组
}, 'image/jpeg')
this.cancelCropper()
},
// 销毁裁剪框
cancelCropper () {
this.cropper.destroy()
this.croppShow = false
this.cropper = null
}
}
结果: