1.上传页
<template>
<view class="page">
<form action="" @submit="formSubmit" @reset="formReset" enctype="multipart/form-data" method="">
<view class="wapper_header">
<button class="cancel" type="default" form-type="reset">取消</button>
<button class="release" form-type="submit">发布</button>
</view>
<view class="" style="width: 93%; margin: 0 auto;">
<input class="" name="title" style="border-bottom: 1px solid #DDDDDD;height: 80rpx;" placeholder="填写标题会有更多赞哦~" />
</view>
<view class="uni-textarea"><textarea name="detail" placeholder="这一刻的想法..." v-model="input_content" /></view>
<view class="uni-list list-pd">
<view class="uni-list-cell cell-pd">
<view class="uni-uploader">
<view class="uni-uploader-head">
<view class="uni-uploader-title"></view>
<view class="uni-uploader-info">{{ imageList.length }}/9</view>
</view>
<view class="uni-uploader-body">
<view class="uni-uploader__files">
<block v-for="(image, index) in imageList" :key="index">
<view class="uni-uploader__file" style="position: relative;">
<image class="uni-uploader__img" mode="aspectFill" :src="image" :data-src="image" @tap="previewImage"></image>
<view class="close-view" @click="close(index)">×</view>
</view>
</block>
<view class="uni-uploader__input-box" v-show="imageList.length < 9">
<view class="uni-uploader__input" @tap="chooseImage" name="file" data-src="imageList"></view>
</view>
</view>
</view>
</view>
</view>
</view>
<view class="tj_goods">
<view class="">添加商品</view>
<view class="tj_sp" @tap="tj_sp">添加商品</view>
</view>
<view class="box" v-if="sishow">
<view class="img_box"><image class="image" :src="goodsname.description_image"></image></view>
<view class="right_boxv">
<view class="one_box">
<text class="publish_name">{{ goodsname.goods_name }}</text>
<text class="deleterr" @click="deleterr">删除</text>
</view>
<view class="two_box">
<text></text>
<text class="goods_pice">¥ {{ goodsname.price }}</text>
</view>
</view>
</view>
<view class="hmy" v-if="sishows">还没有添加商品</view>
<view class="postopbox" v-show="istoggimglist" >
<view class="wapper_header" style="margin-bottom: 0;">
<button class="cancel" @tap="hidecj">取消</button>
<button class="releases" @tap="imglisturl">下一步</button>
</view>
<view class="stylcolor">
<text>{{currentindex+1}}</text>/<text>{{chedimg.length}}</text>
</view>
<swiper @change="swiperTab" style="height: 88%;overflow: hidden;">
<swiper-item class="swiper" v-for="(listItem,listIndex) in chedimg" :key="listIndex">
<view class="l_box">
<image :src="listItem" mode="widthFix" class="l_box_img"></image>
</view>
<button class="cancel" @tap="uploadop" style="margin-left: 20rpx;">裁剪</button>
</swiper-item>
</swiper>
</view>
</form>
</view>
</template>
<script>
import Bus from '../../common/bus.js';
import Config from '@/src/config/index.js';
var sourceType = [['camera'], ['album'], ['camera', 'album']];
var sizeType = [['compressed'], ['original'], ['compressed', 'original']];
function getTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
month.length < 2 ? '0' + month : month;
day.length < 2 ? '0' + day : day;
return year + '-' + month + '-' + day;
}
export default {
data() {
return {
src: '',
currentindex:0,
chedimg:[],
input_content: '',
imageList: [],
sourceTypeIndex: 2,
sourceType: ['拍照', '相册', '拍照或相册'],
sizeTypeIndex: 2,
sizeType: ['压缩', '原图', '压缩或原图'],
countIndex: 8,
count: [1, 2, 3, 4, 5, 6, 7, 8, 9],
bblists: '',
//侧滑返回start
// startX: 0, //点击屏幕起始位置
// movedX: 0, //横向移动的距离
// endX: 0, //接触屏幕后移开时的位置
goodsname: '', //子组件选择的商品
sishow: false, //判断是否添加商品的状态
sishows: true, //判断是否添加商品的状态
imagePath: [],
userId:'' ,//用户id
nickname:'' ,//用户名
issubmit:false,
urls: ["/static/img/xhongxin.png","/static/img/xhongxin.png"],
istoggimglist:false,
url:'_doc/uniapp_temp_1578360834204/canvas/1578360896953.png',
mm:''
};
},
onUnload() {
(this.imageList = []),
(this.sourceTypeIndex = 2),
(this.sourceType = ['拍照', '相册', '拍照或相册']),
(this.sizeTypeIndex = 2),
(this.sizeType = ['压缩', '原图', '压缩或原图']),
(this.countIndex = 8);
},
created() {
var that = this
uni.getStorage({
key: 'userInfo',
success(e) {
that.userId = e.data.userId
that.nickname = e.data.randname
}
})
},
onLoad(option) {
var that = this
uni.getStorage({
key: 'chedimg',
success(e) {
that.chedimg = e.data
let { avatar, type } = option;
if (avatar) {
that.src = avatar
that.chedimg[type] = avatar
that.istoggimglist = true
}
if(type == 0){
that.istoggimglist = true
}
}
})
},
mounted: function() {
var vm = this;
// 用$on事件来接收参数
Bus.$on('val', data => {
vm.goodsname = data;
if (data == '') {
vm.sishow = false;
vm.sishows = true;
} else {
vm.sishows = false;
vm.sishow = true;
}
});
},
methods: {
imglisturl(){
let that = this
let tempFilePaths = this.chedimg
for(let i=0;i<tempFilePaths.length;i++){
uni.uploadFile({
url: Config.baseUrl +'/v1/goods/upload',
filePath: tempFilePaths[i],
name: 'file',
formData: {
'user': 'test'
},
success: (uploadFileRes) => {console.log(uploadFileRes.data)
that.imageList.push(uploadFileRes.data)
this.istoggimglist = false
this.chedimg = []
}
});
if(i==tempFilePaths.length-1){
}
}
},
hidecj(){
this.istoggimglist = false
this.chedimg = []
},
//选取照片
uploadop(){
var that = this
let index = this.currentindex
let src = this.chedimg[index];
console.log(src,'传过去截取的图片',index)
uni.redirectTo({
url: './upload?src=' + src + '&type=' + index,
})
uni.setStorage({ //缓存用户登陆状态
key: 'chedimg',
data: that.chedimg
})
},
// swiper 滑动
swiperTab: function(e) {
this.currentindex = e.detail.current //获取索引
},
//删除商品
deleterr: function(){
this.goodsname = {}
this.sishow = false
},
//添加商品
tj_sp: function() {
uni.navigateTo({
url: './commodityaddition'
});
},
formSubmit: function(e) {
var that = this
if(that.issubmit==false){
that.issubmit=true;
}else{
return false;
}
var bblist = ''
var brand_image = this.imageList[0];
var post_img = this.imageList;
var title = e.detail.value.title;
var content = e.detail.value.detail;
var userid = that.userId;
var nickname = that.nickname;
var goods_id = this.goodsname.id;
if (goods_id == undefined) {
goods_id = -1;
}
if (title == '') {
uni.showModal({
content: '标题不能为空',
showCancel: false
});
that.issubmit = false
return false;
} else if (content == '') {
uni.showModal({
content: '内容不能为空',
showCancel: false
});
that.issubmit = false
return false;
} else if (this.imageList == '') {
uni.showModal({
content: '图片上传中',
showCancel: false
});
that.issubmit = false
return false;
} else {
var top_time = getTime();
uni.request({
url: Config.baseUrl + '/v1/allsocialcon/invitation',
method: 'POST',
data: {
nickname: nickname,
userid: userid,
title: title,
content: content,
brand_image: brand_image,
post_img: post_img,
goods_id: goods_id
},
header: { 'Content-type': 'application/x-www-form-urlencoded;charset=utf-8' },
success: function(res) {
uni.showLoading({
title: '发布成功'
});
},
fail: function(res) {
uni.showToast({
title: '上传图片过大,上传失败'
});
}
});
setTimeout(function() {
uni.hideLoading();
uni.switchTab({
url: './../findings/findings',
success: function(e) {
var page = getCurrentPages()[0];
if (page == undefined || page == null) return;
page.onLoad();
}
});
}, 1000);
}
var userInfo=uni.getStorageSync('userInfo');
that.userId = userInfo.userId
that.nickname = userInfo.randname
},
formReset: function(e) {
this.imageList = [];
this.imagePath = [];
console.log('清空数据');
uni.navigateBack()
},
chooseImage: async function(e) {
var that = this
if (this.imageList.length === 9) {
let isContinue = await this.isFullImg();
console.log("是否继续?", isContinue);
if (!isContinue) {
return;
}
}
await uni.chooseImage({
count:9-this.imageList.length,
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
that.chedimg = tempFilePaths
that.istoggimglist = true
console.log(tempFilePaths , '我是上传的图片publish')
// imgurl = that.src
// tempFilePaths.push(imgurl)
// con
// for(let i=0;i<tempFilePaths.length;i++){
// uni.uploadFile({
// url: Config.baseUrl +'/v1/goods/upload',
// filePath: tempFilePaths[i],
// name: 'file',
// formData: {
// 'user': 'test'
// },
// success: (uploadFileRes) => {console.log(uploadFileRes.data)
// that.imageList.push(uploadFileRes.data)
// console.log(that.imageList,'处理之后的路径')
// }
// });
// if(i==tempFilePaths.length-1){
// }
// }
}
});
},
isFullImg: function() {
return new Promise((res) => {
uni.showModal({
content: "已经有9张图片了,是否清空现有图片?",
success: (e) => {
if (e.confirm) {
this.imageList = [];
res(true);
} else {
res(false)
}
},
fail: () => {
res(false)
}
})
})
},
previewImage: function(e) {
var current = e.target.dataset.src
uni.previewImage({
current: current,
urls: this.imageList
})
},
close(e){
this.imageList.splice(e,1);
},
}
};
</script>
<style scoped>
.postopbox{position: fixed;top: 0;left: 0;background: #000000;width: 100%;height: 100%;z-index: 99}
.l_box{width: 100%;float: left;max-height: 90%;overflow: hidden;margin-bottom: 30rpx;}
.l_box_img{width: 100%;}
.stylcolor{width: 100%;height: 50rpx;text-align: center;color: #FFFFFF;}
.nextstep{padding: 0 8rpx;background: #FFFFFF;color: #000000;margin-right: 40rpx;}
.nextstep_box{width: 100%;text-align: right;}
.jc_btn{padding: 0 8rpx;background: #FFFFFF;color: #000000;}
.footer {
margin-top: 80upx;
}
.cell-pd {
padding: 20upx 30upx;
}
.uni-textarea {
width: auto;
padding: 20upx 25upx;
line-height: 1.6;
height: 150upx;
}
.uni-list::before {
height: 0;
}
.uni-list:after {
height: 0;
}
.list-pd {
margin-top: 0;
}
.close-view {
text-align: center;
line-height: 30upx;
height: 35upx;
width: 35upx;
background: #ef5350;
color: #ffffff;
position: absolute;
top: 1upx;
right: 1upx;
font-size: 35upx;
border-radius: 8upx;
}
.page {
width: 750upx;
height: 100%;
}
.cancel {
background-color: #fff;
color: #333;
width: 112upx;
height: 50upx;
line-height: 50upx;
float: left;
font-size: 28upx;
padding: 0;
text-align: center;
}
.release {
background-color: #000;
color: #fff;
width: 112upx;
height: 50upx;
line-height: 50upx;
float: right;
font-size: 28upx;
padding: 0;
text-align: center;
}
.releases {
background-color: #fff;
color: #000;
width: 112upx;
height: 50upx;
line-height: 50upx;
float: right;
font-size: 28upx;
padding: 0;
text-align: center;
}
.wapper_header {
padding: 80rpx 20rpx 0 20rpx;
overflow: hidden;
margin-bottom: 30rpx;
}
.img_box {
display: flex;
align-items: center;
justify-content: center;
width: 210rpx;
height: 158rpx;
float: left;
margin: 0 20rpx;
}
.img_box image {
width: 210rpx;
height: 158rpx;
}
.box {
width: 100%;
overflow: hidden;
margin-bottom: 20rpx;
padding: 20px 0;
}
.right_boxv {
width: 66%;
overflow: hidden;
float: left;
}
.one_box {
/* display: flex; /
width: 100%;
float: left;
/ align-items: center; /
/ justify-content: space-between; */
}
.two_box {
/* display: flex; /
width: 100%;
float: left;
text-align: right;
/ align-items: center; /
/ justify-content: space-between; */
}
.publish_name {
color: #333333;
font-size: 32rpx;
overflow: hidden;
}
.goods_pice {
font-size: 32rpx;
font-weight: 600;
color: #dc3545;
padding-right: 10px;
}
.three_box {
display: flex;
flex-direction: row-reverse;
}
.three_list {
padding: 0rpx 20rpx;
background: #000000;
color: #fff;
line-height: 44rpx;
margin-left: 22rpx;
}
.y_p {
background: #fff;
color: #000000;
line-height: 46rpx;
}
.bor {
background: #fff;
border: 2rpx solid #000000;
color: #000000;
}
.tj_goods {
width: 94%;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
}
.tj_sp {
background: #000000;
padding: 0 26rpx;
color: #ffffff;
border-radius: 10rpx;
}
.hmy {
width: 100%;
text-align: center;
}
.deleterr{
text-align: right;
float: right;
margin-right: 20rpx;
padding: 2rpx 20rpx;
background: #000000;
color: #fff;
font-size: 12px;
border-radius: 10rpx;
}
.oooppp{width: 200rpx; height: 200rpx;}
</style>
2裁剪页面
<template>
<view class="content" style="background: #000000;padding: 0;">
<view class="cropper-wrapper" style="height:100%">
<canvas
class="cropper"
disable-scroll="true"
@touchstart="touchStart"
@touchmove="touchMove"
@touchend="touchEnd"
:style="{ width: cropperOpt.width, height: cropperOpt.height }"
canvas-id="cropper"
></canvas>
</view>
<view class="cropper-buttons">
<view class="upload" @tap="returntop" style="color: #FFFFFF;">
取消
</view>
<view class="getCropperImage" @tap="getCropperImage" style="color: #FFFFFF;">确定</view>
</view>
</view>
</template>
<script>
import weCropper from '../../common/weCropper.js';
const js_sdk = require('../../components/js_sdk/index.js')
const device = uni.getSystemInfoSync();
const width = device.windowWidth;
const height = device.windowHeight - 50;
console.log(device);
export default {
data() {
return {
cropperOpt: {
src:'',
type:'',
id: 'cropper',
width: width,
height: height,
scale: 2.5,
zoom: 8,
cut: {
x: (width - 345) / 2,
y: (height - 295) / 2,
width: 345,
height: 295
}
},
weCropper: ''
};
},
methods: {
back() {
uni.redirectTo({
url: '../infoDetail/infoDetail'
});
},
touchStart(e) {
this.weCropper.touchStart(e);
},
touchMove(e) {
this.weCropper.touchMove(e);
},
touchEnd(e) {
this.weCropper.touchEnd(e);
},
convertBase64UrlToBlob(dataURI, type) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], { type: type }, { filename: '1111.jpg' });
},
blobToDataURL(blob) {
var a = new FileReader();
a.readAsDataURL(blob); //读取文件保存在result中
a.onload = function(e) {
var getRes = e.target.result; //读取的结果在result中
console.log(getRes);
};
},
// 取消
returntop(){
let vurl = this.src
let type = this.type
uni.redirectTo({
url: './publish?avatar=' + vurl + '&type=' + type
});
// console.log('------------------')
},
getCropperImage() {
let _this = this;
this.weCropper.getCropperImage(avatar => {
let vurl = avatar
let type = _this.type
if(vurl){
// console.log(type,'================>')
uni.redirectTo({
url: './publish?avatar=' + vurl + '&type=' + type
});
} else {
console.log('获取图片失败,请稍后重试');
}
});
},
uploadTap() {
const self = this;
uni.chooseImage({
count: 1, // 默认9
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success(res) {
let src = res.tempFilePaths[0];
// 获取裁剪图片资源后,给data添加src属性及其值
self.weCropper.pushOrign(src);
}
});
}
},
onLoad(option) {
// do something
const cropperOpt = this.cropperOpt;
const src = option.src
this.type = option.type
this.src = option.src
if (src) {
Object.assign(cropperOpt, {
src
});
this.weCropper = new weCropper(cropperOpt)
.on('ready', function(ctx) {})
.on('beforeImageLoad', ctx => {
uni.showToast({
title: '上传中',
icon: 'loading',
duration: 3000
});
})
.on('imageLoad', ctx => {
uni.hideToast();
});
}
}
};
</script>
<style>
.content {
background: #000000;
}
.head-list {
height: 43px;
width: 100%;
background: #ffffff;
justify-content: center;
align-items: center;
display: flex;
border-bottom: 1px solid rgba(244, 244, 244, 1);
}
.head-info {
text-align: center;
font-size: 18px;
color: #000000;
font-weight: bold;
}
.save-box {
position: absolute;
right: 0px;
width: 50px;
height: 43px;
line-height: 43px;
}
.save {
color: rgba(98, 111, 252, 1);
font-size: 16px;
font-weight: 400;
}
.icon-back {
margin-top: 11px;
width: 10px;
height: 18px;
color: #000000;
margin-left: 6px;
}
.icon-back-box {
display: block;
position: absolute;
left: 6px;
height: 43px;
width: 30px;
align-items: center;
}
.cropper {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.cropper-buttons {
background-color: rgba(0, 0, 0, 0.95);
color: #04b00f;
}
.cropper-wrapper {
position: relative;
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
width: 100%;
background-color: #000000;
}
.cropper-buttons {
width: 100vw;
height: 50px;
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
position: fixed;
bottom: 0;
left: 0;
line-height: 50px;
}
.cropper-buttons .upload,
.cropper-buttons .getCropperImage {
width: 50%;
text-align: center;
}
</style>
3.在upload页面引入weCropper.js
(function(global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.weCropper = factory());
}(this, (function() {
'use strict';
/**
- Created by sail on 2017/6/11.
*/
var device = void 0;
var TOUCH_STATE = ['touchstarted', 'touchmoved', 'touchended'];
function firstLetterUpper(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function setTouchState(instance) {
for (var _len = arguments.length, arg = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
arg[_key - 1] = arguments[_key];
}
TOUCH_STATE.forEach(function(key, i) {
if (arg[i] !== undefined) {
instance[key] = arg[i];
}
});
}
function validator(instance, o) {
Object.defineProperties(instance, o);
}
function getDevice() {
if (!device) {
device = wx.getSystemInfoSync();
}
return device;
}
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var classCallCheck = function(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var slicedToArray = function() {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function(arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
var tmp = {};
var DEFAULT = {
id: {
default: 'cropper',
get: function get1(value) {
if (typeof value !== 'string') {}
tmp.id = value;
}
},
width: {
default: 750,
get: function get1(value) {
tmp.width = value;
}
},
height: {
default: 750,
get: function get1(value) {
tmp.height = value;
}
},
scale: {
default: 2.5,
get: function get1(value) {
tmp.scale = value;
}
},
zoom: {
default: 5,
get: function get1(value) {
tmp.zoom = value;
}
},
src: {
default: 'cropper',
get: function get1(value) {
tmp.src = value;
}
},
cut: {
default: {},
get: function get1(value) {
tmp.cut = value;
}
},
onReady: {
default: null,
get: function get1(value) {
tmp.ready = value;
}
},
onBeforeImageLoad: {
default: null,
get: function get1(value) {
tmp.beforeImageLoad = value;
}
},
onImageLoad: {
default: null,
get: function get1(value) {
tmp.imageLoad = value;
}
},
onBeforeDraw: {
default: null,
get: function get1(value) {
tmp.beforeDraw = value;
}
}
};
/**
- Created by sail on 2017/6/11.
*/
function prepare() {
var self = this;
var _getDevice = getDevice(),
windowWidth = _getDevice.windowWidth;
self.attachPage = function() {
var pages = getCurrentPages
// 获取到当前page上下文
();
var pageContext = pages[pages.length - 1];
// 把this依附在Page上下文的wecropper属性上,便于在page钩子函数中访问
pageContext.wecropper = self;
};
self.createCtx = function() {
var id = self.id;
if (id) {
self.ctx = wx.createCanvasContext(id);
}
};
self.deviceRadio = windowWidth / 750;
self.deviceRadio=self.deviceRadio.toFixed(2)
}
/**
*/
function observer() {
var self = this;
var EVENT_TYPE = ['ready', 'beforeImageLoad', 'beforeDraw', 'imageLoad'];
self.on = function(event, fn) {
if (EVENT_TYPE.indexOf(event) > -1) {
if (typeof fn === 'function') {
event === 'ready' ? fn(self) : self['on' + firstLetterUpper(event)] = fn;
}
}
return self;
};
}
/**
- Created by sail on 2017/6/11.
*/
function methods() {
var self = this;
var deviceRadio = self.deviceRadio;
console.log(JSON.stringify(self));
var boundWidth = self.width; // 裁剪框默认宽度,即整个画布宽度
var boundHeight = self.height; // 裁剪框默认高度,即整个画布高度
var _self$cut = self.cut,
_self$cut$x = _self$cut.x,
x = _self$cut$x === undefined ? 0 : _self$cut$x,
_self$cut$y = _self$cut.y,
y = _self$cut$y === undefined ? 0 : _self$cut$y,
_self$cut$width = _self$cut.width,
width = _self$cut$width === undefined ? boundWidth : _self$cut$width,
_self$cut$height = _self$cut.height,
height = _self$cut$height === undefined ? boundHeight : _self$cut$height;
self.updateCanvas = function() {
if (self.croperTarget) {
// 画布绘制图片
self.ctx.drawImage(self.croperTarget, self.imgLeft, self.imgTop, self.scaleWidth, self.scaleHeight);
}
typeof self.onBeforeDraw === 'function' && self.onBeforeDraw(self.ctx, self);
self.setBoundStyle // 设置边界样式
();
self.ctx.draw();
return self;
};
self.pushOrign = function(src) {
self.src = src;
typeof self.onBeforeImageLoad === 'function' && self.onBeforeImageLoad(self.ctx, self);
uni.getImageInfo({
src: src,
success: function success(res) {
var innerAspectRadio = res.width / res.height;
self.croperTarget = res.path||src;
if (innerAspectRadio < width / height) {
self.rectX = x;
self.baseWidth = width;
self.baseHeight = width / innerAspectRadio;
self.rectY = y - Math.abs((height - self.baseHeight) / 2);
} else {
self.rectY = y;
self.baseWidth = height * innerAspectRadio;
self.baseHeight = height;
self.rectX = x - Math.abs((width - self.baseWidth) / 2);
}
self.imgLeft = self.rectX;
self.imgTop = self.rectY;
self.scaleWidth = self.baseWidth;
self.scaleHeight = self.baseHeight;
self.updateCanvas();
typeof self.onImageLoad === 'function' && self.onImageLoad(self.ctx, self);
}
});
self.update();
return self;
};
self.getCropperImage = function() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var id = self.id;
var ARG_TYPE = toString.call(args[0]);
switch (ARG_TYPE) {
case '[object Object]':
var _args$0$quality = args[0].quality,
quality = _args$0$quality === undefined ? 10 : _args$0$quality;
console.log("quality--"+quality);
uni.canvasToTempFilePath({
canvasId: id,
x: x,
y: y,
width: width,
height: height,
destWidth: width * quality / (deviceRadio * 10),
destHeight: height * quality / (deviceRadio * 10),
success: function success(res) {
console.log(res);
typeof args[args.length - 1] === 'function' && args[args.length - 1](res.tempFilePath);
}
});
break;
case '[object Function]':
uni.canvasToTempFilePath({
canvasId: id,
x: x,
y: y,
fileType:"jpg",
width: width,
height: height,
destWidth: width ,
destHeight: height,
success: function success(res) {
typeof args[args.length - 1] === 'function' && args[args.length - 1](res.tempFilePath);
}
});
break;
}
return self;
};
}
/**
- Created by sail on 2017/6/11.
*/
function update() {
var self = this;
if (!self.src) return;
self.__oneTouchStart = function(touch) {
self.touchX0 = touch.x;
self.touchY0 = touch.y;
};
self.__oneTouchMove = function(touch) {
var xMove = void 0,
yMove = void 0;
//计算单指移动的距离
if (self.touchended) {
return self.updateCanvas();
}
xMove = touch.x - self.touchX0;
yMove = touch.y - self.touchY0;
var imgLeft = self.rectX + xMove;
var imgTop = self.rectY + yMove;
self.outsideBound(imgLeft, imgTop);
self.updateCanvas();
};
self.__twoTouchStart = function(touch0, touch1) {
var xMove = void 0,
yMove = void 0,
oldDistance = void 0;
self.touchX1 = self.rectX + self.scaleWidth / 2;
self.touchY1 = self.rectY + self.scaleHeight / 2;
//计算两指距离
xMove = touch1.x - touch0.x;
yMove = touch1.y - touch0.y;
oldDistance = Math.sqrt(xMove * xMove + yMove * yMove);
self.oldDistance = oldDistance;
};
self.__twoTouchMove = function(touch0, touch1) {
var xMove = void 0,
yMove = void 0,
newDistance = void 0;
var scale = self.scale,
zoom = self.zoom;
// 计算二指最新距离
xMove = touch1.x - touch0.x;
yMove = touch1.y - touch0.y;
newDistance = Math.sqrt(xMove * xMove + yMove * yMove
// 使用0.005的缩放倍数具有良好的缩放体验
);
self.newScale = self.oldScale + 0.001 * zoom * (newDistance - self.oldDistance);
// 设定缩放范围
self.newScale <= 1 && (self.newScale = 1);
self.newScale >= scale && (self.newScale = scale);
self.scaleWidth = self.newScale * self.baseWidth;
self.scaleHeight = self.newScale * self.baseHeight;
var imgLeft = self.touchX1 - self.scaleWidth / 2;
var imgTop = self.touchY1 - self.scaleHeight / 2;
self.outsideBound(imgLeft, imgTop);
self.updateCanvas();
};
self.__xtouchEnd = function() {
self.oldScale = self.newScale;
self.rectX = self.imgLeft;
self.rectY = self.imgTop;
};
}
/**
- Created by sail on 2017/6/11.
*/
var handle = {
// 图片手势初始监测
touchStart: function touchStart(e) {
var self = this;
var _etouches[0],
touch1 = _e$touches[1];
console.log(JSON.stringify(touch1));
if(!touch0.x){
touch0.x=touch0.clientX;
touch0.y=touch0.clientY;
if(touch1){
touch1.x=touch1.clientX;
touch1.y=touch1.clientY;
}
}
setTouchState(self, true, null, null
//计算第一个触摸点的位置,并参照改点进行缩放
);
self.__oneTouchStart(touch0
// 两指手势触发
);
if (e.touches.length >= 2) {
self.__twoTouchStart(touch0, touch1);
}
},
// 图片手势动态缩放
touchMove: function touchMove(e) {
var self = this;
var _e$touches2 = slicedToArray(e.touches, 2),
touch0 = _e$touches2[0],
touch1 = _e$touches2[1];
if(!touch0.x){
touch0.x=touch0.clientX;
touch0.y=touch0.clientY;
if(touch1){
touch1.x=touch1.clientX;
touch1.y=touch1.clientY;
}
}
setTouchState(self, null, true
// 单指手势时触发
);
if (e.touches.length === 1) {
self.__oneTouchMove(touch0);
}
// 两指手势触发
if (e.touches.length >= 2) {
self.__twoTouchMove(touch0, touch1);
}
},
touchEnd: function touchEnd(e) {
var self = this;
setTouchState(self, false, false, true);
self.__xtouchEnd();
}
};
/**
- Created by sail on 1017/6/12.
*/
function cut() {
var self = this;
var deviceRadio = self.deviceRadio;
var boundWidth = self.width; // 裁剪框默认宽度,即整个画布宽度
var boundHeight = self.height;
// 裁剪框默认高度,即整个画布高度
var _self$cut = self.cut,
_self$cut$x = _self$cut.x,
x = _self$cut$x === undefined ? 0 : _self$cut$x,
_self$cut$y = _self$cut.y,
y = _self$cut$y === undefined ? 0 : _self$cut$y,
_self$cut$width = _self$cut.width,
width = _self$cut$width === undefined ? boundWidth : _self$cut$width,
_self$cut$height = _self$cut.height,
height = _self$cut$height === undefined ? boundHeight : _self$cut$height;
/**
* 设置边界
* @param imgLeft 图片左上角横坐标值
* @param imgTop 图片左上角纵坐标值
*/
self.outsideBound = function(imgLeft, imgTop) {
self.imgLeft = imgLeft >= x ? x : self.scaleWidth + imgLeft - x <= width ? x + width - self.scaleWidth : imgLeft;
self.imgTop = imgTop >= y ? y : self.scaleHeight + imgTop - y <= height ? y + height - self.scaleHeight : imgTop;
};
/**
* 设置边界样式
* @param color 边界颜色
*/
self.setBoundStyle = function() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$color = _ref.color,
color = _ref$color === undefined ? '#04b00f' : _ref$color,
_ref$mask = _ref.mask,
mask = _ref$mask === undefined ? 'rgba(0, 0, 0, 0.3)' : _ref$mask,
_ref$lineWidth = _ref.lineWidth,
lineWidth = _ref$lineWidth === undefined ? 1 : _ref$lineWidth;
// 绘制半透明层
self.ctx.beginPath();
self.ctx.setFillStyle(mask);
self.ctx.fillRect(0, 0, x, boundHeight);
self.ctx.fillRect(x, 0, width, y);
self.ctx.fillRect(x, y + height, width, boundHeight - y - height);
self.ctx.fillRect(x + width, 0, boundWidth - x - width, boundHeight);
self.ctx.fill
// 设置边界左上角样式
// 为使边界样式处于边界外边缘,此时x、y均要减少lineWidth
();
self.ctx.beginPath();
self.ctx.setStrokeStyle(color);
self.ctx.setLineWidth(lineWidth);
self.ctx.moveTo(x - lineWidth, y + 10 - lineWidth);
self.ctx.lineTo(x - lineWidth, y - lineWidth);
self.ctx.lineTo(x + 10 - lineWidth, y - lineWidth);
self.ctx.stroke
// 设置边界左下角样式
// 为使边界样式处于边界外边缘,此时x要减少lineWidth、y要增加lineWidth
();
self.ctx.beginPath();
self.ctx.setStrokeStyle(color);
self.ctx.setLineWidth(lineWidth);
self.ctx.moveTo(x - lineWidth, y + height - 10 + lineWidth);
self.ctx.lineTo(x - lineWidth, y + height + lineWidth);
self.ctx.lineTo(x + 10 - lineWidth, y + height + lineWidth);
self.ctx.stroke
// 设置边界右上角样式
// 为使边界样式处于边界外边缘,此时x要增加lineWidth、y要减少lineWidth
();
self.ctx.beginPath();
self.ctx.setStrokeStyle(color);
self.ctx.setLineWidth(lineWidth);
self.ctx.moveTo(x + width - 10 + lineWidth, y - lineWidth);
self.ctx.lineTo(x + width + lineWidth, y - lineWidth);
self.ctx.lineTo(x + width + lineWidth, y + 10 - lineWidth);
self.ctx.stroke
// 设置边界右下角样式
// 为使边界样式处于边界外边缘,此时x、y均要增加lineWidth
();
self.ctx.beginPath();
self.ctx.setStrokeStyle(color);
self.ctx.setLineWidth(lineWidth);
self.ctx.moveTo(x + width + lineWidth, y + height - 10 + lineWidth);
self.ctx.lineTo(x + width + lineWidth, y + height + lineWidth);
self.ctx.lineTo(x + width - 10 + lineWidth, y + height + lineWidth);
self.ctx.stroke();
};
}
var version = '1.1.4';
var weCropper = function() {
function weCropper(params) {
classCallCheck(this, weCropper);
var self = this;
var _default = {};
validator(self, DEFAULT);
Object.keys(DEFAULT).forEach(function(key) {
_default[key] = DEFAULT[key].default;
});
Object.assign(self, _default, params);
self.prepare();
self.attachPage();
self.createCtx();
self.observer();
self.cutt();
self.methods();
self.init();
self.update();
return self;
}
createClass(weCropper, [{
key: 'init',
value: function init() {
var self = this;
var src = self.src;
self.version = __version__;
typeof self.onReady === 'function' && self.onReady(self.ctx, self);
if (src) {
self.pushOrign(src);
}
setTouchState(self, false, false, false);
self.oldScale = 1;
self.newScale = 1;
return self;
}
}]);
return weCropper;
}();
Object.assign(weCropper.prototype, handle);
weCropper.prototype.prepare = prepare;
weCropper.prototype.observer = observer;
weCropper.prototype.methods = methods;
weCropper.prototype.cutt = cut;
weCropper.prototype.update = update;
return weCropper;
})));