uniapp下上传图片后图片裁剪加图片旋转,支持H5和app
【代码】uniapp下上传图片后图片裁剪加图片旋转,支持H5和app。
·
效果图
代码如下
<template>
<view class="container" v-show="isShow">
<view>
<view class="cropper-content">
<view v-if="isShowImg" class="uni-corpper"
:style="'width:' + cropperInitW + 'px;height:' + cropperInitH + 'px;background:#000'">
<view class="uni-corpper-content" :style="
'width:' +
cropperW +
'px;height:' +
cropperH +
'px;left:' +
cropperL +
'px;top:' +
cropperT +
'px'
">
<image :src="imageSrc" :style="'width:' + cropperW + 'px;height:' + cropperH + 'px'"></image>
<view class="uni-corpper-crop-box" @touchstart.stop="contentStartMove"
@touchmove.stop="contentMoveing" @touchend.stop="contentTouchEnd" :style="
'left:' + cutL + 'px;top:' + cutT + 'px;right:' + cutR + 'px;bottom:' + cutB + 'px'
">
<view class="uni-cropper-view-box">
<view class="uni-cropper-dashed-h"></view>
<view class="uni-cropper-dashed-v"></view>
<!-- 截图区域顶部 -->
<view class="uni-cropper-line-t" data-drag="top" @touchstart.stop="dragStart"
@touchmove.stop="dragMove"></view>
<!-- 截图区域右侧 -->
<view class="uni-cropper-line-r" data-drag="right" @touchstart.stop="dragStart"
@touchmove.stop="dragMove"></view>
<!-- 截图区域底部 -->
<view class="uni-cropper-line-b" data-drag="bottom" @touchstart.stop="dragStart"
@touchmove.stop="dragMove"></view>
<!-- 截图区域左侧 -->
<view class="uni-cropper-line-l" data-drag="left" @touchstart.stop="dragStart"
@touchmove.stop="dragMove"></view>
<!-- 右下角截图滑块 -->
<view class="uni-cropper-point point-t" data-drag="top" @touchstart.stop="dragStart"
@touchmove.stop="dragMove"></view>
<view class="uni-cropper-point point-tr" data-drag="topTight"></view>
<view class="uni-cropper-point point-r" data-drag="right" @touchstart.stop="dragStart"
@touchmove.stop="dragMove"></view>
<view class="uni-cropper-point point-rb" data-drag="rightBottom"
@touchstart.stop="dragStart" @touchmove.stop="dragMove"></view>
<view class="uni-cropper-point point-b" data-drag="bottom" @touchstart.stop="dragStart"
@touchmove.stop="dragMove" @touchend.stop="dragEnd"></view>
<view class="uni-cropper-point point-bl" data-drag="bottomLeft"></view>
<view class="uni-cropper-point point-l" data-drag="left" @touchstart.stop="dragStart"
@touchmove.stop="dragMove"></view>
<view class="uni-cropper-point point-lt" data-drag="leftTop"></view>
</view>
</view>
</view>
</view>
</view>
<view class="cropper-config">
<view class="tips">{{msg}}</view>
<view class="button-box">
<view class="btn">
<img @tap="chooseImage" src="https://imgbos.ai.hanyastar.cn/stu/photo/photo_white.png"
style="height: 44rpx;height: 37rpx;">
</view>
<!-- <button type="warn" @click="chooseImage">重选</button> -->
<view class="finish-photo btn" style="">
<img @tap="finish" class="ok-img" src="https://imgbos.ai.hanyastar.cn/stu/photo/ok.png" />
</view>
<!-- <text class="btn" style="color: #FFF;line-height: 142rpx;text-align: right;" @click="rotateImgTap">旋转</text> -->
<view class="btn" style="">
<img @tap="rotateImgTap" src="https://imgbos.ai.hanyastar.cn/stu/photo/rotate.png"
style="height: 44rpx;height: 37rpx;" />
</view>
<!-- <text class="btn" style="color: #FFF;line-height: 142rpx;text-align: right;" @click="previewImg">预览</text> -->
<!-- <button type="warn" @click="finish">完成</button> -->
</view>
</view>
<canvas canvas-id="myCanvas" :style="
'position:absolute;border: 2px solid red; width:' +
imageW +
'px;height:' +
imageH +
'px;top:-9999px;left:-9999px;'
"></canvas>
</view>
</view>
</template>
<script>
let sysInfo = uni.getSystemInfoSync();
let SCREEN_WIDTH = sysInfo.screenWidth;
let SCREEN_HEIGHT = sysInfo.windowHeight;
let PAGE_X, // 手按下的x位置
PAGE_Y, // 手按下y的位置
PR = sysInfo.pixelRatio, // dpi
T_PAGE_X, // 手移动的时候x的位置
T_PAGE_Y, // 手移动的时候Y的位置
CUT_L, // 初始化拖拽元素的left值
CUT_T, // 初始化拖拽元素的top值
CUT_R, // 初始化拖拽元素的
CUT_B, // 初始化拖拽元素的
CUT_W, // 初始化拖拽元素的宽度
CUT_H, // 初始化拖拽元素的高度
IMG_RATIO, // 图片比例
IMG_REAL_W, // 图片实际的宽度
IMG_REAL_H, // 图片实际的高度
DRAFG_MOVE_RATIO = 1, //移动时候的比例,
INIT_DRAG_POSITION = 100, // 初始化屏幕宽度和裁剪区域的宽度之差,用于设置初始化裁剪的宽度
DRAW_IMAGE_W = sysInfo.screenWidth; // 设置生成的图片宽度
export default {
/**
* 页面的初始数据
*/
data() {
return {
originImg: '',
rotateTime: 1, // 旋转次数
imageSrc: "",
isShow: false,
isShowImg: false,
// 初始化的宽高
cropperInitW: SCREEN_WIDTH,
cropperInitH: SCREEN_HEIGHT,
// 动态的宽高
cropperW: SCREEN_WIDTH,
cropperH: SCREEN_HEIGHT - 100,
// 动态的left top值
cropperL: 0,
cropperT: 0,
transL: 0,
transT: 0,
// 图片缩放值
scaleP: 0,
imageW: 0,
imageH: 0,
// 裁剪框 宽高
cutL: 0,
cutT: 0,
cutB: SCREEN_WIDTH,
cutR: "100%",
qualityWidth: DRAW_IMAGE_W,
innerAspectRadio: DRAFG_MOVE_RATIO,
};
},
props: {
/* 截图质量,压缩比 */
quality: {
type: Number | String,
default: 1,
},
msg: {
type: String,
default: '一次只选一题,更容易搜到答案'
},
/*
* 传入图片路径,将跳过选择图片步骤直接进入截图界面。
* 需要特别注意:H5端 Canvas 内绘制的图像需要支持跨域访问才能成功。
*/
imgSrc: String,
/* 输出图片类型:仅支持png格式或jpg格式 */
fileType: {
type: String,
default: "png",
validator: function(t) {
// 这个值必须匹配下列字符串中的一个
return t === "png" || t === "jpg";
},
},
/* 截取类型,自由截取free;固定比例截取(正方形)fixed */
cropperType: {
type: String,
default: "free",
validator: function(t) {
// 这个值必须匹配下列字符串中的一个
return t === "free" || t === "fixed" || t === "ratio";
},
},
ratio: {
type: Number,
default: 1,
},
},
created() {},
onLoad(opt) {},
mounted() {
if (this.imgSrc) {
this.imageSrc = this.imgSrc;
this.originImg = this.imgSrc;
console.log(this.imgSrc, "imgSrc");
console.log(this.cropperType, "cropperType");
this.loadImage();
this.isShow = true;
this.isShowImg = true;
}
},
methods: {
//1中使用到的将blob转化为file方法 和图片的压缩方法
objectURLToBlob(url, callback) {
var http = new XMLHttpRequest();
http.open('GET', url, true);
http.responseType = 'blob';
http.onload = function(e) {
if (this.status == 200 || this.status === 0) {
callback(this.response);
}
};
http.send();
},
async comprossImage(imgSrc, maxWidth, func) {
if (!imgSrc) return 0;
return new Promise((resolve, reject) => {
uni.getImageInfo({
src: imgSrc,
success(res) {
let img = new Image();
img.src = res.path;
console.log(img);
let canvas = document.createElement('canvas');
let obj = new Object();
obj.img = img;
obj.canvas = canvas;
resolve(func(obj));
}
});
});
},
rotateImg(img, direction, canvas, times = 1) {
console.log('开始旋转');
//最小与最大旋转方向,图片旋转4次后回到原方向
var min_step = 0;
var max_step = 3;
if (img == null) return;
//img的高度和宽度不能在img元素隐藏后获取,否则会出错
var height = img.height;
var width = img.width;
let maxWidth = 500;
let canvasWidth = width; //图片原始长宽
let canvasHeight = height;
let base = canvasWidth / canvasHeight;
width = canvasWidth;
height = canvasHeight;
var step = 0;
if (step == null) {
step = min_step;
}
if (direction == 'right') {
step += times;
//旋转到原位置,即超过最大值
step > max_step && (step = min_step);
} else if (direction == 'left') {
step -= times;
step < min_step && (step = max_step);
} else {
//不旋转
step = 0;
}
//旋转角度以弧度值为参数
var degree = (step * 90 * Math.PI) / 180;
var ctx = canvas.getContext('2d');
// console.log(degree)
// console.log(step)
switch (step) {
case 1:
console.log('右旋转 90度');
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, 0, -height, width, height);
break;
case 2:
//console.log('旋转 180度')
canvas.width = width;
canvas.height = height;
ctx.rotate(degree);
ctx.drawImage(img, -width, -height, width, height);
break;
case 3:
console.log('左旋转 90度');
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, -width, 0, width, height);
break;
default:
//不旋转
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
break;
}
let baseStr = canvas.toDataURL('image/jpeg', 1);
// console.log(baseStr)
// return baseStr;
// replace("data:image/jpeg;base64,", "")
// 将base64转化为blob文件进行图片上传,(考虑到转化后再上传耗费时间暂时没有使用,如果需要base64ToPath 方法可百度或者私信我)
// base64ToPath(baseStr).then(tempPath => {
// this.uploadBgImg(tempPath)
// });
// 自定义上传请求
//this.uploadBaseImg(baseStr);
return baseStr
},
// 旋转图片
async rotateImgTap() {
// #ifdef H5
var img = null;
var canvas = null;
await this.comprossImage(this.imageSrc, 50000, function(e) {
img = e.img;
canvas = e.canvas;
});
let src = this.rotateImg(img, 'right', canvas, this.rotateTime);
if (this.rotateTime == 4) {
this.rotateTime = 1
} else {
this.rotateTime = this.rotateTime + 1
}
console.info(this.rotateTime)
this.setData({
imageSrc: src,
});
this.loadImage();
this.isShow = true;
// #endif
// #ifdef APP-PLUS
var img = {};
var _this = this
if(this.rotateTime == 1) {
uni.showLoading({
title: "图片旋转中...",
});
plus.zip.compressImage({
src: this.originImg,
dst: "_doc/uniapp_temp" + '/compressed/' + Math.round(new Date()) + '.png',
format: 'png',
quality: 80,
width: 'auto',
height: 'auto',
rotate: 90,
},
function(event) {
console.info(event.target)
_this.setData({
imageSrc: event.target
});
_this.loadImage();
_this.isShow = true;
uni.hideLoading();
},
function(error) {
uni.hideLoading();
uni.showToast({
title: "图片不支持旋转!",
icon: "none",
});
})
//this.rotate(this.originImg)
} else {
_this.setData({
imageSrc: this.originImg,
});
_this.loadImage();
_this.isShow = true;
}
if (this.rotateTime == 2) {
this.rotateTime = 1
} else {
this.rotateTime = this.rotateTime + 1
}
console.info(this.rotateTime)
// #endif
},
rotate(tempFilePaths) {
const that = this
var _this = this;
uni.getImageInfo({
// 获取图片的信息
src: tempFilePaths,
success: (res1) => {
console.log(res1)
// 将canvas1的内容复制到canvas2中
let canvasContext = uni.createCanvasContext('myCanvas', this)
let rate = res1.height / res1.width
let width = 375 / rate
let height = 375
canvasContext.translate(0, 0)
canvasContext.rotate((90 * Math.PI) / 180)
canvasContext.drawImage(tempFilePaths, 0, -999, width, 999)
canvasContext.draw(true, (data) => {
// 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中
uni.canvasToTempFilePath({
// 把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功。
x:0,
y:0,
canvasId: 'myCanvas',
fileType: 'png',
width:375,
quality: 1, //图片质量
success(res2) {
// 调用uni.uploadFile上传图片即可
console.log(res2.tempFilePath)
_this.setData({
imageSrc: res2.tempFilePath,
});
_this.loadImage();
_this.isShow = true;
}
}, _this)
});
}
})
},
setData: function(obj) {
let that = this;
Object.keys(obj).forEach(function(key) {
that.$set(that.$data, key, obj[key]);
});
},
/* 选择图片 */
chooseImage: function(e) {
console.info('点击了')
var _this = this;
uni.chooseImage({
count: 1,
success: function(res) {
//#ifndef H5
let index = res.tempFilePaths[0].lastIndexOf(".");
let imgUrl = res.tempFilePaths[0].substr(index + 1);
if (imgUrl != "png" && imgUrl != "jpg" && imgUrl != "jpeg") {
uni.$u.toast('请上传jpg、jpeg、png类型的图片');
return
}
//#endif
//#ifdef H5
if (res.tempFiles[0].type !== 'image/jpeg' && res.tempFiles[0].type !==
'image/png' && res.tempFiles[0].type !== 'image/jpeg') {
uni.$u.toast('请上传jpg、jpeg、png类型的图片');
return
}
//#endif
if (res.tempFiles[0].size / 1024 < 1024 * 1024 * 20) {
_this.originImg = res.tempFilePaths[0]
_this.setData({
imageSrc: res.tempFilePaths[0],
});
_this.loadImage();
_this.isShow = true;
} else {
uni.showToast({
title: '图片大小不能超过20M,当前大小' + (res.tempFiles[0].size / 1024).toFixed(
2) + 'KB',
icon: 'none'
})
}
},
});
},
/* 将图片加载到画布 */
loadImage: function() {
var _this = this;
uni.showLoading({
title: "图片加载中...",
});
/* 获取图片信息 */
uni.getImageInfo({
src: _this.imageSrc,
success: function success(res) {
let imgH = res.height;
let imgW = res.width;
// let IMG_SCR_H_R = SCREEN_HEIGHT / imgH;
// let IMG_SCR_W_R = SCREEN_WIDTH / imgW;
/* 图片的宽高比 */
IMG_RATIO = imgW / imgH;
/**
* 如果图片更高一些,为确保图片能够完整在视窗内显示需如下处理
* 1. 缩放图片的高为 视窗高度减去底部菜单按钮高度(120)
* 2. 根据图片缩放后的高度,根据图片宽高比计算图片的宽度
* 3. 如果步骤2计算的图片宽度大于屏幕宽度,则需要再次调整图片宽度为视窗宽度-margin(10)
* 4. 根据步骤3的宽度,结合图片宽高比重新计算图片的高度
*/
if (IMG_RATIO < 1 && (SCREEN_HEIGHT - 133) * IMG_RATIO < SCREEN_WIDTH - 10) {
IMG_REAL_W = (SCREEN_HEIGHT - 133) * IMG_RATIO;
IMG_REAL_H = SCREEN_HEIGHT - 133;
} else {
IMG_REAL_W = SCREEN_WIDTH - 10;
IMG_REAL_H = IMG_REAL_W / IMG_RATIO;
}
console.log("ratio", "=====1====");
/* 初始化裁剪区域的位置和形状 */
let [cutT, cutB, cutL, cutR] = _this.initCutArea(IMG_RATIO, IMG_REAL_H,
IMG_REAL_W);
_this.setData({
/* 裁剪区域的宽高同图片尺寸 */
cropperW: IMG_REAL_W,
cropperH: IMG_REAL_H,
/* 上下左右各留一定的margin已便更好的拖动裁剪区域 */
cropperL: Math.ceil((SCREEN_WIDTH - IMG_REAL_W) / 2),
/* 留出底部操作按钮位置 70 */
cropperT: uni.getStorageSync("navHeight"),
cutL: cutL,
cutT: cutT,
cutR: cutR,
cutB: cutB,
// 图片缩放值
imageW: IMG_REAL_W,
imageH: IMG_REAL_H,
scaleP: IMG_REAL_W / SCREEN_WIDTH,
qualityWidth: DRAW_IMAGE_W,
innerAspectRadio: IMG_RATIO,
});
_this.setData({
isShowImg: true,
});
uni.hideLoading();
},
});
},
initCutArea(IMG_RATIO, IMG_REAL_H, IMG_REAL_W) {
let _this = this;
/* 自由裁剪裁剪区域默认覆盖整个图片 */
let cutT = 0;
let cutB = 0;
let cutL = 0;
let cutR = 0;
console.log("ratio", "=====2====" + this.cropperType);
/* 正方形裁剪,初始化裁剪区域为正方形并居中 */
if (_this.cropperType == "fixed") {
// if (IMG_RATIO < 1) {
// /* 图片比较高 */
// cutT = (IMG_REAL_H - IMG_REAL_W) / 2;
// cutB = (IMG_REAL_H - IMG_REAL_W) / 2;
// } else {
// /* 图片比较宽 */
// cutL = (IMG_REAL_W - IMG_REAL_H) / 2;
// cutR = (IMG_REAL_W - IMG_REAL_H) / 2;
// }
if (IMG_RATIO < 1) {
/* 图片比较高 */
cutT = (IMG_REAL_H - IMG_REAL_W) / 2;
cutB = (IMG_REAL_H - IMG_REAL_W) / 2;
} else {
/* 图片比较宽 */
cutL = (IMG_REAL_W - IMG_REAL_H) / 2;
cutR = (IMG_REAL_W - IMG_REAL_H) / 2;
}
}
/* 固定比例裁剪,初始化裁剪区域比例和设定值相同 */
if (_this.cropperType == "ratio") {
let ratio = +_this.ratio;
console.log("ratio", "1111")
if (IMG_RATIO < 1) {
console.log("ratio", "1111112222")
/* 图片比较高 */
if (IMG_REAL_W / ratio > IMG_REAL_H) {
cutT = cutB = 0;
cutL = cutR = (IMG_REAL_W - IMG_REAL_H * ratio) / 2;
} else {
cutR = cutL = 0;
cutT = cutB = (IMG_REAL_H - IMG_REAL_W / ratio) / 2;
}
// cutR = cutL = 0;
// cutT = cutB= (IMG_REAL_H - IMG_REAL_W/5*3)/2
} else {
console.log("ratio", "111111333")
/* 图片比较宽 */
if (IMG_REAL_H * ratio > IMG_REAL_W) {
cutL = cutR = 0;
cutB = cutT = (IMG_REAL_H - IMG_REAL_W / ratio) / 2;
} else {
cutT = cutB = 0;
cutL = cutR = (IMG_REAL_W - IMG_REAL_H * ratio) / 2;
}
}
}
console.info(cutT, cutB, cutL, cutR)
return [cutT, cutB, cutL, cutR];
},
// 拖动时候触发的touchStart事件
contentStartMove(e) {
PAGE_X = e.touches[0].pageX;
PAGE_Y = e.touches[0].pageY;
},
// 拖动时候触发的touchMove事件
contentMoveing(e) {
var _this = this;
var dragLengthX = (PAGE_X - e.touches[0].pageX) * DRAFG_MOVE_RATIO;
var dragLengthY = (PAGE_Y - e.touches[0].pageY) * DRAFG_MOVE_RATIO;
// 左移
if (dragLengthX > 0) {
//向左移动,剪裁区域超过了当前图片的左边,判定移动距离,为初始裁剪区域距离左边距
if (this.cutL - dragLengthX < 0) dragLengthX = this.cutL;
} else {
//向右移动,剪裁区域超过了当前图片的右边,判定移动距离,为初始裁剪区域距离右边距
if (this.cutR + dragLengthX < 0) dragLengthX = -this.cutR;
}
if (dragLengthY > 0) {
//向上移动,剪裁区域超过了当前图片的上边,判定移动距离,为初始裁剪区域距离顶部边距
if (this.cutT - dragLengthY < 0) dragLengthY = this.cutT;
} else {
//向下移动,剪裁区域超过了当前图片的底部,判定移动距离,为初始裁剪区域距离底部边距
if (this.cutB + dragLengthY < 0) dragLengthY = -this.cutB;
}
this.setData({
cutL: this.cutL - dragLengthX,
cutT: this.cutT - dragLengthY,
cutR: this.cutR + dragLengthX,
cutB: this.cutB + dragLengthY,
});
PAGE_X = e.touches[0].pageX;
PAGE_Y = e.touches[0].pageY;
},
contentTouchEnd() {},
transBase64() {},
// 获取图片尺寸信息
previewImg() {
try {
var _this = this;
uni.showLoading({
title: "图片生成中...",
});
// 将图片写入画布
const ctx = uni.createCanvasContext("myCanvas", _this);
ctx.drawImage(_this.imageSrc, 0, 0, IMG_REAL_W, IMG_REAL_H);
ctx.draw(true, () => {
// 获取画布要裁剪的位置和宽度 均为百分比 * 画布中图片的宽度 保证了在微信小程序中裁剪的图片模糊 位置不对的问题 canvasT = (_this.cutT / _this.cropperH) * (_this.imageH / pixelRatio)
var canvasW = ((_this.cropperW - _this.cutL - _this.cutR) / _this.cropperW) * IMG_REAL_W;
var canvasH = ((_this.cropperH - _this.cutT - _this.cutB) / _this.cropperH) * IMG_REAL_H;
var canvasL = (_this.cutL / _this.cropperW) * IMG_REAL_W;
var canvasT = (_this.cutT / _this.cropperH) * IMG_REAL_H;
uni.canvasToTempFilePath({
x: canvasL,
y: canvasT,
width: canvasW,
height: canvasH,
// destWidth: canvasW,
// destHeight: canvasH,
quality: +this.quality,
fileType: this.fileType,
canvasId: "myCanvas",
success: function(res) {
uni.hideLoading();
// 成功获得地址的地方
uni.previewImage({
current: "", // 当前显示图片的http链接
urls: [res.tempFilePath], // 需要预览的图片http链接列表
});
},
fail: function(err) {
uni.hideLoading();
uni.showToast({
title: "图片截取失败!",
icon: "none",
});
},
},
_this
);
});
} catch (e) {}
},
/* 完成裁剪,输出裁剪后的图片路径 */
finish: function() {
var _this = this;
uni.showLoading({
title: "图片生成中...",
});
// 将图片写入画布
const ctx = uni.createCanvasContext("myCanvas", _this);
ctx.drawImage(_this.imageSrc, 0, 0, IMG_REAL_W, IMG_REAL_H);
ctx.draw(true, () => {
// 获取画布要裁剪的位置和宽度 均为百分比 * 画布中图片的宽度 保证了在微信小程序中裁剪的图片模糊 位置不对的问题 canvasT = (_this.cutT / _this.cropperH) * (_this.imageH / pixelRatio)
var canvasW = ((_this.cropperW - _this.cutL - _this.cutR) / _this.cropperW) * IMG_REAL_W;
var canvasH = ((_this.cropperH - _this.cutT - _this.cutB) / _this.cropperH) * IMG_REAL_H;
var canvasL = (_this.cutL / _this.cropperW) * IMG_REAL_W;
var canvasT = (_this.cutT / _this.cropperH) * IMG_REAL_H;
uni.canvasToTempFilePath({
x: canvasL,
y: canvasT,
width: canvasW,
height: canvasH,
// destWidth: canvasW,
// destHeight: canvasH,
quality: +this.quality,
fileType: this.fileType,
canvasId: "myCanvas",
success: function(res) {
uni.hideLoading();
// 成功获得地址的地方
// #ifdef H5
_this.$emit("getImg", res.tempFilePath);
// #endif
// #ifdef APP-PLUS
plus.io.resolveLocalFileSystemURL(res.tempFilePath, function(entry) {
entry.file(function(file) {
console.log(file)
var reader = new plus.io.FileReader();
reader.readAsDataURL(file);
reader.onloadend = function(e) {
// console.log(e.target.result)
const resBase64 = e.target.result
.replace('data:audio/mpeg;base64,',
'')
console.log(resBase64)
_this.$emit("getImg", resBase64);
}
})
})
// #endif
_this.isShow = false;
},
fail: function(err) {
uni.hideLoading();
uni.showToast({
title: "图片截取失败!",
icon: "none",
});
},
},
_this
);
});
},
// 设置大小的时候触发的touchStart事件
dragStart(e) {
T_PAGE_X = e.touches[0].pageX;
T_PAGE_Y = e.touches[0].pageY;
CUT_L = this.cutL;
CUT_R = this.cutR;
CUT_B = this.cutB;
CUT_T = this.cutT;
},
// 设置大小的时候触发的touchMove事件
dragMove(e) {
// this.cropperType == "fixed" ? this.fixedScaleDrag(e) : this.freeDrag(e);
this[this.cropperType + "Drag"](e);
},
/* 固定比例(正方形)截取 ,只有右下角裁剪滑动拖动有效*/
fixedDrag(e) {
var _this = this;
var dragType = e.target.dataset.drag;
switch (dragType) {
case "rightBottom":
var dragLengthX = (T_PAGE_X - e.touches[0].pageX) * DRAFG_MOVE_RATIO;
// var dragLengthY = (T_PAGE_Y - e.touches[0].pageY) * DRAFG_MOVE_RATIO;
// if (CUT_B + dragLengthY < 0) dragLengthY = -CUT_B;
if (CUT_R + dragLengthX < 0) dragLengthX = -CUT_R;
/* 右侧和底部同比变化 */
let cutB = CUT_B + dragLengthX;
let cutR = CUT_R + dragLengthX;
/* 越界判断 */
if (_this.cutB == 0 && cutB < 0) return;
if (_this.cutR == 0 && cutR < 0) return;
(_this.cutB > 0 || CUT_B == 0) &&
this.setData({
cutB: cutB < 0 ? 0 : cutB,
cutR: cutR,
});
break;
default:
break;
}
},
/* 等比例截图,只能通过右下角的滑块改变截图区域 */
ratioDrag(e) {
var _this = this;
var dragType = e.target.dataset.drag;
switch (dragType) {
case "rightBottom":
var dragLengthX = (T_PAGE_X - e.touches[0].pageX) * DRAFG_MOVE_RATIO;
// var dragLengthY = (T_PAGE_Y - e.touches[0].pageY) * DRAFG_MOVE_RATIO;
// if (CUT_B + dragLengthY < 0) dragLengthY = -CUT_B;
if (CUT_R + dragLengthX < 0) dragLengthX = -CUT_R;
/* 右侧和底部同比变化 */
let cutB = CUT_B + dragLengthX / _this.ratio;
let cutR = CUT_R + dragLengthX;
/* 越界判断 */
if (_this.cutB == 0 && cutB < 0) return;
if (_this.cutR == 0 && cutR < 0) return;
(_this.cutB > 0 || CUT_B == 0) &&
this.setData({
cutB: cutB < 0 ? 0 : cutB,
cutR: cutR,
});
break;
default:
break;
}
},
/* 自由截取,整个裁剪边框均能拖动 */
freeDrag(e) {
var _this = this;
var dragType = e.target.dataset.drag;
switch (dragType) {
case "right":
var dragLength = (T_PAGE_X - e.touches[0].pageX) * DRAFG_MOVE_RATIO;
if (CUT_R + dragLength < 0) dragLength = -CUT_R;
this.setData({
cutR: CUT_R + dragLength,
});
break;
case "left":
var dragLength = (T_PAGE_X - e.touches[0].pageX) * DRAFG_MOVE_RATIO;
if (CUT_L - dragLength < 0) dragLength = CUT_L;
if (CUT_L - dragLength > this.cropperW - this.cutR)
dragLength = CUT_L - (this.cropperW - this.cutR);
this.setData({
cutL: CUT_L - dragLength,
});
break;
case "top":
var dragLength = (T_PAGE_Y - e.touches[0].pageY) * DRAFG_MOVE_RATIO;
if (CUT_T - dragLength < 0) dragLength = CUT_T;
if (CUT_T - dragLength > this.cropperH - this.cutB)
dragLength = CUT_T - (this.cropperH - this.cutB);
this.setData({
cutT: CUT_T - dragLength,
});
break;
case "bottom":
var dragLength = (T_PAGE_Y - e.touches[0].pageY) * DRAFG_MOVE_RATIO;
if (CUT_B + dragLength < 0) dragLength = -CUT_B;
this.setData({
cutB: CUT_B + dragLength,
});
break;
case "rightBottom":
var dragLengthX = (T_PAGE_X - e.touches[0].pageX) * DRAFG_MOVE_RATIO;
var dragLengthY = (T_PAGE_Y - e.touches[0].pageY) * DRAFG_MOVE_RATIO;
if (CUT_B + dragLengthY < 0) dragLengthY = -CUT_B;
if (CUT_R + dragLengthX < 0) dragLengthX = -CUT_R;
let cutB = CUT_B + dragLengthY;
let cutR = CUT_R + dragLengthX;
this.setData({
cutB: cutB,
cutR: cutR,
});
break;
default:
break;
}
},
},
};
</script>
<style lang="scss" scoped>
/* pages/uni-cropper/index.wxss */
.container {
background-color: #fff;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 50px;
display: block;
align-items: center;
flex-direction: column;
z-index: 998;
height: 100vh;
}
.cropper-config {
position: fixed;
z-index: 1;
bottom: 10px;
left: 0;
right: 0;
width: 100%;
padding: 0rpx 120rpx;
box-sizing: border-box;
margin: 0 auto;
/* padding: 20upx 40upx; */
.tips {
height: 42rpx;
font-size: 30rpx;
color: #FFFFFF;
text-align: center;
z-index: 1;
}
}
.button-box {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
width: 100%;
.btn {}
.finish-photo {
width: 142rpx;
height: 142rpx;
background: #45D6DD;
border-radius: 100%;
display: flex;
align-items: center;
justify-content: center;
.ok-img {
width: 82rpx;
}
}
}
.button-box button {
width: 25%;
line-height: 35px;
height: 35px;
}
.cropper-content {
width: 100%;
min-height: 750upx;
}
.uni-corpper {
position: relative;
overflow: hidden;
box-sizing: border-box;
margin: 0 auto;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-tap-highlight-color: transparent;
-webkit-touch-callout: none;
}
.uni-corpper-content {
position: relative;
position: absolute;
top: 0;
bottom: 0;
left: 0px !important;
right: 0;
margin: auto;
max-width: 100%;
max-height: 100%;
}
.uni-corpper-content image {
display: block;
width: 100%;
min-width: 0 !important;
max-width: none !important;
/* height: 100%; */
min-height: 0 !important;
/* max-height: none !important; */
max-height: calc(100vh - 100upx);
margin: 0 auto;
image-orientation: 0deg !important;
}
/* 移动图片效果 */
.uni-cropper-drag-box {
position: absolute;
z-index: 1;
top: 0;
right: 0;
bottom: 0;
left: 0;
cursor: move;
background: #00000050;
}
/* 内部的信息 */
.uni-corpper-crop-box {
position: absolute;
z-index: 2;
max-height: calc(100vh - 100upx);
background: rgba(56, 50, 50, 0.479);
}
.uni-corpper-crop-box .uni-cropper-view-box {
position: relative;
display: block;
overflow: visible;
width: 100%;
height: 100%;
max-height: calc(100vh - 100upx);
outline: 5upx solid #646161;
outline-color: #FFFFFF;
}
/* 横向虚线 */
.uni-cropper-dashed-h {
position: absolute;
top: 33.33333333%;
left: 0;
width: 100%;
height: 33.33333333%;
border-top: 1upx dashed #FFFFFF50;
border-bottom: 1upx dashed #FFFFFF50;
}
/* 纵向虚线 */
.uni-cropper-dashed-v {
position: absolute;
top: 0;
left: 33.33333333%;
width: 33.33333333%;
height: 100%;
border-right: 1upx dashed #FFFFFF50;
border-left: 1upx dashed #FFFFFF50;
}
/* 四个方向的线 为了之后的拖动事件*/
.uni-cropper-line-t {
position: absolute;
top: 0;
left: 0;
display: block;
width: 100%;
height: 3upx;
cursor: n-resize;
opacity: 0.1;
background-color: white;
}
.uni-cropper-line-t::before {
position: absolute;
z-index: 11;
top: 50%;
right: 0upx;
bottom: 0;
width: 100%;
height: 41upx;
content: "";
-webkit-transform: translate3d(0, -50%, 0);
transform: translate3d(0, -50%, 0);
background: transparent;
}
.uni-cropper-line-r {
position: absolute;
top: 0;
right: 0upx;
display: block;
width: 3upx;
height: 100%;
cursor: e-resize;
opacity: 0.1;
background-color: white;
}
.uni-cropper-line-r::before {
position: absolute;
z-index: 11;
top: 0;
bottom: 0;
left: 50%;
width: 41upx;
height: 100%;
content: "";
-webkit-transform: translate3d(-50%, 0, 0);
transform: translate3d(-50%, 0, 0);
background: transparent;
}
.uni-cropper-line-b {
position: absolute;
bottom: 0;
left: 0;
display: block;
width: 100%;
height: 3upx;
cursor: s-resize;
opacity: 0.1;
background-color: white;
}
.uni-cropper-line-b::before {
position: absolute;
z-index: 11;
top: 50%;
right: 0upx;
bottom: 0;
width: 100%;
height: 41upx;
content: "";
-webkit-transform: translate3d(0, -50%, 0);
transform: translate3d(0, -50%, 0);
background: transparent;
}
.uni-cropper-line-l {
position: absolute;
top: 0;
left: 0;
display: block;
width: 3upx;
height: 100%;
cursor: w-resize;
opacity: 0.1;
background-color: white;
}
.uni-cropper-line-l::before {
position: absolute;
z-index: 11;
top: 0;
bottom: 0;
left: 50%;
width: 41upx;
height: 100%;
content: "";
-webkit-transform: translate3d(-50%, 0, 0);
transform: translate3d(-50%, 0, 0);
background: transparent;
}
.uni-cropper-point {
position: absolute;
z-index: 3;
width: 5upx;
height: 5upx;
opacity: 0.75;
background-color: rgb(145, 132, 132);
}
.point-t {
top: -3upx;
left: 50%;
margin-left: -3upx;
cursor: n-resize;
}
.point-tr {
top: -3upx;
left: 100%;
margin-left: -3upx;
cursor: n-resize;
}
.point-r {
top: 50%;
left: 100%;
margin-top: -3upx;
margin-left: -3upx;
cursor: n-resize;
}
.point-rb {
position: absolute;
z-index: 1112;
top: 100%;
left: 100%;
width: 36upx;
height: 36upx;
cursor: n-resize;
-webkit-transform: translate3d(-50%, -50%, 0);
transform: translate3d(-50%, -50%, 0);
opacity: 1;
background-color: rgb(231, 222, 222);
}
.point-b {
top: 100%;
left: 50%;
margin-top: -3upx;
margin-left: -3upx;
cursor: n-resize;
}
.point-bl {
top: 100%;
left: 0;
margin-top: -3upx;
margin-left: -3upx;
cursor: n-resize;
}
.point-l {
top: 50%;
left: 0;
margin-top: -3upx;
margin-left: -3upx;
cursor: n-resize;
}
.point-lt {
top: 0;
left: 0;
margin-top: -3upx;
margin-left: -3upx;
cursor: n-resize;
}
/* 裁剪框预览内容 */
.uni-cropper-viewer {
position: relative;
overflow: hidden;
width: 100%;
height: 100%;
}
.uni-cropper-viewer image {
position: absolute;
z-index: 2;
}
</style>
更多推荐
已为社区贡献2条内容
所有评论(0)