一、插件
一、安装html2canvas、vue-cropper
npm i html2canvas --save
npm i vue-cropper -S
二、在main.js注册vue-cropper组件
import VueCropper from 'vue-cropper'
Vue.use(VueCropper)
三、页面中引入html2canvas
import html2canvas from "html2canvas"
二、主要代码
<template>
<div>
<h2 style="font-size: 20px" @click="tailoring">裁剪</h2>
<!--继续写页面的其他内容 pop_alert可封装成组件使用-->
<p>截图展示的图片</p>
<img style="border: 5px solid #000000" :src="uploadImg" alt="" />
<div class="pop_alert" v-if="show">
<vueCropper
@mouseenter.native="enter"
@mouseleave.native="leave"
ref="cropper"
:img="uploadImg"
:outputSize="option.size"
:outputType="option.outputType"
:info="true"
:full="option.full"
:canMove="option.canMove"
:canMoveBox="option.canMoveBox"
:original="option.original"
:autoCrop="option.autoCrop"
:fixed="option.fixed"
:fixedNumber="option.fixedNumber"
:centerBox="option.centerBox"
:infoTrue="option.infoTrue"
:fixedBox="option.fixedBox"
style="background-image: none"
></vueCropper>
<div class="btn_box">
<div @click="save">确认截图</div>
<div @click="close">取消</div>
</div>
</div>
</div>
</template>
<script>
import html2canvas from 'html2canvas'
export default {
data() {
return {
option: {
info: true,
outputSize: 0.8,
outputType: 'jpeg',
canScale: false,
autoCrop: false,
fixedBox: false,
fixed: false,
fixedNumber: [7, 5],
full: true,
canMove: false,
canMoveBox: true,
original: false,
centerBox: false,
infoTrue: true,
},
uploadImg: '',
show: false,
}
},
methods: {
tailoring() {
this.$nextTick(() => {
html2canvas(document.body, {}).then(canvas => {
let dataURL = canvas.toDataURL('image/png')
console.log(dataURL, 'dataURL')
this.uploadImg = dataURL
this.show = true
})
})
},
enter() {
if (this.uploadImg == '') {
return
}
this.$refs.cropper.startCrop()
},
leave() {
this.$refs.cropper.stopCrop()
},
save() {
this.$refs.cropper.getCropData(data => {
console.log(data)
this.show = false
})
},
close() {
this.show = false
},
},
}
</script>
<style>
.pop_alert {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
border: 1px dashed red;
background-color: #000000;
}
.btn_box {
position: absolute;
top: 0;
color: red;
right: 0;
font-size: 30px;
display: flex;
align-items: center;
z-index: 6666;
}
</style>
链接: https://www.cnblogs.com/zwbsoft/p/16657954.html