效果图:
剪切之后:
js资源:Vue下的图片剪切的资源
注意这里只能使用v-show,要保证节点是存在的,不然初始化画布的时候会报错
<div class="clip-wp" id="clip-wp" v-show="isClip" >
<!--这个是个是canvas的容器,init的时候的传参需要传这个id-->
<div id="container"></div>
<button id="save-img" @click="saveImg">保存</button>
</div>
引入资源:(具体看你的资源文件放置的位置)
import clip from './clip/index';//剪裁区域的渲染的构造函数
data中添加:
noScoll:function(evt){
this.isClip && evt.preventDefault();
},
clip:null,///canvas 实例
相关的方法,在methods中:
//这是初始化画布的方法
/**
*@param {container} 放置画布的容器,根据自己实际的容器名称进行配置
*@param {this} 当前的vue实例
*@param {showImgUrl} 用于保存生成的图片的变量,后面通过 this.showImgUrl 获取这个图片实例
*/
clipImg(event){
//此处的event是选择完图片之后获取到的文件列表
this.clip = new clip('container',this,'showImgUrl');
console.log(this.clip)
this.clip.init(event.target.files[0]);
console.log(this.isClip)
this.isClip = true;
//将页面的公共按钮小喇叭隐藏
this.$route.meta.tabBarShow = false;
//useCapture: 默认值为false(即 使用事件冒泡)
//但是这个的作用是什么
document.body.addEventListener('touchmove',this.noScoll,false);
},
//保存截取的图片并停止监听
saveImg(){
this.clip.save();
this.isClip = false;
document.body.removeEventListener('touchmove',this.noScoll,false);
},
//转成 blob 对象 -- 用于将canvas的画布内容转换成blob对象,再生成临时的链接,用于预览
dataURLtoBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
},
//转成 File 对象 -- 将canvas的画布内容生成file文件格式,即是选择文件时候获取到的格式,用于做上传
dataURLtoFile(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
// 这里的 'share.png' 是自定义的文件名
return new File([u8arr],'share.png',{ type: mime });
},
额外的样式
.clip-wp{
position: fixed;
width: 100%;
top: 0;
bottom: 0;
z-index: 11;
background-color: #000;
text-align: center;
z-index:600;//剪切图片区域的层级,对小喇叭进行覆盖
}
#container{
background-color: #000;
text-align: center;
width: 100%;
left: 0;
right: 0;
//这里要再调整
top: 40px;
bottom: 160px;
margin: 0 auto;
position: absolute;
}
#save-img{
position: absolute;
// bottom: 20px;
top:92vh;//自己加上的
width: 90%;
left: 5%;
//这里也要再调整
height: 84px;
line-height: 84px;
font-size:30px;
color: #fff;
background-color: #0094e7;
border-radius: 40px;
}