diff --git a/App.vue b/App.vue index ee65c57..89526a8 100644 --- a/App.vue +++ b/App.vue @@ -2,7 +2,7 @@ export default { onLaunch: function() { - + }, onShow: function() { console.log('App Show') diff --git a/api/6155/BlueHelper.js b/api/6155/BlueHelper.js new file mode 100644 index 0000000..82dd23d --- /dev/null +++ b/api/6155/BlueHelper.js @@ -0,0 +1,671 @@ +export default { + featrueValueCallback: null,//蓝牙特征变化回调 + BleChangeCallback:null,//蓝牙状态变化回调 + //引导用户打开蓝牙 + showBluetoothGuide: function(showTip) { + let platform = process.env.UNI_PLATFORM; + + + var openBlueSetting = function() { + // 判断平台类型 + if (platform === 'mp-weixin') { + uni.openSetting(); + } else if (platform === 'app-plus' || platform === 'app') { + //---------------------------------------------------------------- + const osName = plus.os.name; + + if (osName === 'iOS') { + // iOS 平台打开蓝牙设置 + plus.runtime.openURL('App-Prefs:root=Bluetooth', function() { + console.log('成功打开蓝牙设置'); + }, function(err) { + console.error('打开蓝牙设置失败:' + err.message); + uni.showModal({ + title: '提示', + content: '无法自动打开蓝牙设置,请手动前往设置 > 蓝牙 进行操作。', + showCancel: false + }); + }); + } else if (osName === 'Android') { + // Android 平台打开蓝牙设置 + try { + const Intent = plus.android.importClass('android.content.Intent'); + const Settings = plus.android.importClass('android.provider.Settings'); + const main = plus.android.runtimeMainActivity(); + const intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS); + main.startActivity(intent); + } catch (e) { + console.error('打开蓝牙设置失败:' + e.message); + // 尝试使用通用设置页面作为备选方案 + plus.runtime.openURL('settings://', function() { + console.log('打开系统设置成功,请手动找到蓝牙选项'); + }, function() { + uni.showModal({ + title: '提示', + content: '无法自动打开蓝牙设置,请手动前往设置页面开启蓝牙。', + showCancel: false + }); + }); + } + } else { + uni.showModal({ + title: '提示', + content: '当前系统不支持自动打开蓝牙设置,请手动操作。', + showCancel: false + }); + } + + + //-------------------------------------------------------------------- + } else if (platform === 'mp-alipay') { + uni.openSetting(); + } + + } + + if (showTip !== undefined) { + openBlueSetting(); + return; + } + if (platform === 'mp-weixin' || platform === 'app-plus' || platform === 'mp-alipay' || platform === 'app') { + uni.showModal({ + title: '蓝牙未开启', + content: '请在系统设置中打开蓝牙以使用此功能', + success: (res) => { + if (res.confirm) { + openBlueSetting(); + } + } + }); + } else { + console.log("当前平台不支持打开系统设置" + platform); + } + + + }, + //获取蓝牙适配器状态 + CheckBlue: function(callback) { + + uni.getBluetoothAdapterState({ + success(res1) { + + console.log("当前蓝牙适配器状态:" + JSON.stringify(res1)) + if (callback) { + callback(res1); + } + + }, + fail(ex1) { + console.log("检查蓝牙状态异常:" + JSON.stringify(ex1)); + if (callback) { + if (ex1.code == 10000) { + console.log("未初始化蓝牙适配器"); + } + let res1 = { + available: false, + discovering: false + } + callback(res1); + } + }, + complete() { + + } + }); + }, + //初始化蓝牙模块 + OpenBlue: function(isCheckState, callback, availCallback) { + + var these = this; + + var init = function() { + uni.openBluetoothAdapter({ + success: (res) => { + console.log("蓝牙初始化成功:" + JSON.stringify(res)); + if (callback) { + callback(); + } + uni.onBluetoothAdapterStateChange(function(state) { + console.log('蓝牙状态发生变化:' + JSON.stringify(state)); + if(this.BleChangeCallback){ + this.BleChangeCallback() + } + }) + }, + fail: function(ex2) { + console.log("蓝牙初始化失败:" + JSON.stringify(ex2)) + if (ex2.code == '10001') { + console.log("手机蓝牙未打开或设备不支持蓝牙"); + + + if (availCallback) { + availCallback(); + } else { + these.showBluetoothGuide(); + } + } + } + }); + } + if (isCheckState) { + this.CheckBlue(function(res1) { + if (res1.available) { + if (callback) { + callback(); + } + return; + } + init(); + }) + } else { + init(); + } + + + + }, + //关闭蓝牙模块,停止搜索、断开所有连接 + CloseBlue: function(callback) { + + this.StopSearch(); + + this.disconnectDevice(); + + uni.closeBluetoothAdapter({ + success: () => { + console.log("蓝牙模块已关闭"); + if (callback) { + callback(); + } + } + }); + }, + //开始搜索新设备 + StartSearch: function(callback) { + + var these = this; + + //发现新设备 + var onDeviceFound = function() { + uni.onBluetoothDeviceFound(function(res) { + console.log("发现新设备:" + JSON.stringify(res)); + if (callback) { + callback(res); + } + }) + } + //开始搜索 + var Search = function() { + uni.startBluetoothDevicesDiscovery({ + services: ["0xFFE0"], + allowDuplicatesKey: false, + success: (res) => { + console.log('开始搜索蓝牙设备成功'); + onDeviceFound(); + }, + fail: (err) => { + console.log(`搜索蓝牙设备失败: ${err.errMsg}`); + } + }); + + } + //先检查蓝牙状态是可用 + this.CheckBlue(function(res1) { + if (res1.available) { + if (!res1.discovering) { + Search(); + } else { + console.log("当前蓝牙正在搜索设备") + } + + } else { + these.OpenBlue(false, Search, () => { + these.showBluetoothGuide(); + }); + } + }); + + + + }, + //停止搜索 + StopSearch: function() { + uni.stopBluetoothDevicesDiscovery({ + success: (res) => { + console.log("停止搜索蓝牙设备成功") + }, + fail() { + console.log("无法停止蓝牙搜索") + } + }); + }, + //获取已连接的设备 + getLinkBlue: function(callback) { + uni.getConnectedBluetoothDevices({ + services: ["0xFFE0"], + success: (res) => { + if (callback) { + callback(res); + + } + }, + fail: function(ex) { + console.log("获取已连接设备异常"); + if (callback) { + callback({ + devices: [] + }); + } + } + }) + }, + //连接某个设备 + LinkBlue: function(deviceId, callback, error) { + + this.StopSearch(); + var these = this; + let key = "linkedDevices"; + var store = uni.getStorageInfoSync(); + var f = store.keys.find(function(v) { + return v == key; + }); + var linkedDevices = []; + if (f) { + var str = uni.getStorageSync(key); + if (str) { + linkedDevices = JSON.parse(str); + }else{ + linkedDevices=[]; + } + + } + //连接成功的回调 + var lindedCallback = function () { + + let c = linkedDevices.find(function (v) { + return v.deviceId == deviceId; + }); + + if (c) { + console.log("连接成功开始监听特征变化") + //监听设备的特征变化 + uni.notifyBLECharacteristicValueChange({ + deviceId: deviceId, + serviceId: c.notifyServiceid, + characteristicId: c.notifyCharactId, + state: true, + success: function (res) { + console.log("开始监听成功。。。。") + if(res.errCode=='0'){ + //订阅特征值 + uni.onBLECharacteristicValueChange(function(data){ + // data.characteristicId + // data.deviceId + // data.serviceId + // data.value + console.log("监听到特征值:"+JSON.stringify(data)); + + if(these.featrueValueCallback){ + these.featrueValueCallback(data); + } + }); + + } + } + }); + } + + if (callback) { + callback(deviceId); + } + } + + var linkState = function(res) { + console.log("获取已连接的设备回调" + JSON.stringify(res)) + let flag = res.devices.find(function(v) { + if (v.deviceId == deviceId) { + return true; + } + return false; + }); + if (flag) { + console.log("设备状态已连接"); + + lindedCallback(deviceId); + + return; + } else { + console.log("设备未连接"); + linkDevice(deviceId); + } + } + + var linkDevice = function(id) { + console.log("正在连接"+id); + uni.createBLEConnection({ + deviceId: id, + timeout: 30000, + success: function(info) { + + console.log("连接成功"); + + uni.setBLEMTU({ + deviceId: id, + mtu: 512, + success: () => { + console.log("mtu设置成功"); + if(linkedDevices){ + console.log("11111"+JSON.stringify(linkedDevices)); + f = linkedDevices.find(function (v) { + return v.deviceId == id; + }); + }else{ + console.log("22222") + f=null; + } + + + + if (!f) { + console.log("缓存中没有找到该设备") + + these.getLinkBlue(function (res) { + if (res.devices && res.devices.length) { + let f = res.devices.find(function (v) { + return v.deviceId == id; + }); + linkedDevices.push(f); + uni.setStorageSync(key, JSON.stringify(linkedDevices)); + + getService(id); + + } + + }); + + + } else { + console.log("缓存中已连接过"); + if (!f.services) { + getService(id); + } else { + + lindedCallback(id); + + } + } + }, + fail: function() { + console.log("mtu设置失败") + } + }); + + }, + fail: function(ex) { + if (error) { + console.log("蓝牙连接失败" + JSON.stringify(error)); + error(ex); + } + } + }); + } + //获取服务 + var getService = function(id) { + + var repeatCnt = 0; + var startgetService = function() { + uni.getBLEDeviceServices({ + deviceId: id, + success: function(res) { + if (res.services && res.services.length > 0) { + console.log("获取到服务:" + JSON.stringify(res)); + + linkedDevices.find(function(v) { + if (v.deviceId == id) { + v.services = res.services; + } + }); + uni.setStorageSync(key, JSON.stringify(linkedDevices)); + var promises = []; + for (var i = 0; i < res.services.length; i++) { + let service = res.services[i]; + promises.push(getFeatrus(id, service.uuid)); + } + + Promise.all(promises) + .then(results => { + console.log('所有操作成功完成', results); + + lindedCallback(id); + + }) + .catch(error => { + console.error('至少一个操作失败', error); + }); + + + } else { + repeatCnt++; + if (repeatCnt > 5) { + + lindedCallback(id); + + return; + } + setTimeout(function() { + startgetService(id); + }, 500); + } + } + }) + } + + setTimeout(function() { + startgetService(id); + }, 1000); + } + //获取特性 + var getFeatrus = function(id, serviceId) { + var promise = new Promise((resolve, reject) => { + uni.getBLEDeviceCharacteristics({ + deviceId: id, + serviceId: serviceId, + success: (res) => { + console.log("获取到特征:" + JSON.stringify(res)); + + //写特征 + let writeChar = res.characteristics.find(char => + char.uuid.indexOf("FFE1") > -1 + ); + //通知特征 + let notiChar = res.characteristics.find(char => + char.uuid.indexOf("FFE2") > -1 + ); + + linkedDevices.find(function(v) { + if (v.deviceId == id) { + if (!v.Characteristics) { + v.Characteristics = []; + } + v.Characteristics = v.Characteristics.concat(res + .characteristics); + + if (writeChar) { + v.writeServiceId = serviceId; + v.wirteCharactId = writeChar.uuid; + } + + if (notiChar) { + v.notifyServiceid = serviceId; + v.notifyCharactId = notiChar.uuid; + } + } + }); + + uni.setStorageSync(key, JSON.stringify(linkedDevices)); + resolve(res); + }, + fail: (ex) => { + console.log("获取特征出现异常:" + JSON.stringify(ex)); + resolve(ex); + } + }); + }); + return promise; + } + + //监测蓝牙状态变化 + uni.onBLEConnectionStateChange(function(res) { + if (!res.connected) { + console.log("蓝牙断开连接" + res.deviceId + ""); + // lindDevice(res.deviceId); + } + }); + + console.log("正在获取蓝牙适配器状态") + this.CheckBlue((res) => { + console.log("蓝牙状态:" + JSON.stringify(res)); + if (res.available) { + this.getLinkBlue(linkState); + } else { + console.log("蓝牙适配器不可用,正在初始化"); + this.OpenBlue(false, () => { + this.getLinkBlue(linkState); + }, () => { + console.log("请引导用户打开蓝牙"); + these.showBluetoothGuide(); + }) + } + + }); + + + }, + //断开连接 + disconnectDevice: function(deviceId) { + + var disconnect = function(id) { + uni.closeBLEConnection({ + deviceId: id, + success: (res) => { + console.log("蓝牙连接已断开"); + + } + }); + } + if (deviceId) { + disconnect(deviceId); + return; + } + //断开所有已连接的设备 + this.getLinkBlue(function(res) { + if (res.devices && res.devices.length > 0) { + for (var i = 0; i < res.devices.length; i++) { + let item = res.devices[i]; + disconnect(item.deviceId); + } + + } else { + console.log("无连接设备"); + } + }); + + }, + //发送二进制数据 + sendData: function(deviceid, buffer) { + + console.log("准备向设备发送数据,deviceid=" + deviceid); + return new Promise((resolve, reject) => { + if (!deviceid) { + reject(`deviceid为空,请输入要发送的设备`); + return; + } + console.log("准备发送数据包"); + let key = "linkedDevices"; + var store = uni.getStorageInfoSync(); + var f = store.keys.find(function(v) { + return v == key; + }); + console.log("倒计时:5"); + var linkedDevices = []; + if (f) { + var str = uni.getStorageSync(key); + if (str) { + linkedDevices = JSON.parse(str); + } + + } + console.log("倒计时:4"); + if (linkedDevices && linkedDevices.length && linkedDevices.length > 0) { + console.log("倒计时:3"); + f = linkedDevices.find(function(v) { + return v.deviceId == deviceid; + + }); + console.log("f=" + JSON.stringify(f)); + // console.log("deviceid=" + deviceid); + console.log("倒计时:2"); + if (f) { + console.log("倒计时:1"); + uni.writeBLECharacteristicValue({ + deviceId: f.deviceId, + serviceId: f.writeServiceId, + characteristicId: f.wirteCharactId, + value: buffer, + success: () => { + console.log("发送数据成功"); + resolve(); + }, + fail: (err) => { + console.log("发送数据失败" + JSON.stringify(err)); + reject(`发送数据失败: ${err.errMsg}`); + }, + complete: function() { + console.log("发送数据complete"); + } + }); + } else { + reject(`已连接设备中无法找到此设备`); + // console.log("警报:已连接设备中无法找到此设备") + } + + } else { + console.log("检测到未与设备建立连接"); + reject(`检测到未与设备建立连接`); + } + + + }); + }, + sendDataNew: function(deviceid, serviceId, characteristicId, buffer) { + + console.log("准备向设备发送数据,deviceid=" + deviceid); + return new Promise((resolve, reject) => { + uni.writeBLECharacteristicValue({ + deviceId: deviceid, + serviceId: serviceId, + characteristicId: characteristicId, + value: buffer, + success: () => { + console.log("发送数据成功"); + resolve(); + }, + fail: (err) => { + console.log("发送数据失败" + JSON.stringify(err)); + reject(`发送数据失败: ${err.errMsg}`); + }, + complete: function() { + console.log("发送数据complete"); + } + }); + + + + + + }); + } + +} + + diff --git a/components/BottomSlideMenuPlus/BottomSlideMenuPlus.vue b/components/BottomSlideMenuPlus/BottomSlideMenuPlus.vue new file mode 100644 index 0000000..af0dd3b --- /dev/null +++ b/components/BottomSlideMenuPlus/BottomSlideMenuPlus.vue @@ -0,0 +1,258 @@ + + + + + \ No newline at end of file diff --git a/components/MessagePopup/MessagePopup.vue b/components/MessagePopup/MessagePopup.vue new file mode 100644 index 0000000..a5faf71 --- /dev/null +++ b/components/MessagePopup/MessagePopup.vue @@ -0,0 +1,381 @@ + + + + + \ No newline at end of file diff --git a/components/Progress/Progress.vue b/components/Progress/Progress.vue new file mode 100644 index 0000000..697e69a --- /dev/null +++ b/components/Progress/Progress.vue @@ -0,0 +1,129 @@ + + + + + \ No newline at end of file diff --git a/manifest.json b/manifest.json index cfd69b3..86e2a73 100644 --- a/manifest.json +++ b/manifest.json @@ -151,6 +151,6 @@ "uniStatistics" : { "enable" : false }, - "vueVersion" : "3", + "vueVersion" : "2", "locale" : "auto" } diff --git a/static/images/6155/DeviceDetail/add.png b/static/images/6155/DeviceDetail/add.png new file mode 100644 index 0000000..3488847 Binary files /dev/null and b/static/images/6155/DeviceDetail/add.png differ diff --git a/static/images/6155/DeviceDetail/battry.png b/static/images/6155/DeviceDetail/battry.png new file mode 100644 index 0000000..7c812ac Binary files /dev/null and b/static/images/6155/DeviceDetail/battry.png differ diff --git a/static/images/6155/DeviceDetail/equip.png b/static/images/6155/DeviceDetail/equip.png new file mode 100644 index 0000000..c9bab86 Binary files /dev/null and b/static/images/6155/DeviceDetail/equip.png differ diff --git a/static/images/6155/DeviceDetail/fan.png b/static/images/6155/DeviceDetail/fan.png new file mode 100644 index 0000000..3481c63 Binary files /dev/null and b/static/images/6155/DeviceDetail/fan.png differ diff --git a/static/images/6155/DeviceDetail/fuLamp.png b/static/images/6155/DeviceDetail/fuLamp.png new file mode 100644 index 0000000..34c68a1 Binary files /dev/null and b/static/images/6155/DeviceDetail/fuLamp.png differ diff --git a/static/images/6155/DeviceDetail/mainLamp.png b/static/images/6155/DeviceDetail/mainLamp.png new file mode 100644 index 0000000..838b901 Binary files /dev/null and b/static/images/6155/DeviceDetail/mainLamp.png differ diff --git a/static/images/6155/DeviceDetail/open.png b/static/images/6155/DeviceDetail/open.png new file mode 100644 index 0000000..b2f321e Binary files /dev/null and b/static/images/6155/DeviceDetail/open.png differ diff --git a/static/images/6155/DeviceDetail/param.png b/static/images/6155/DeviceDetail/param.png new file mode 100644 index 0000000..10cbd63 Binary files /dev/null and b/static/images/6155/DeviceDetail/param.png differ diff --git a/static/images/6155/DeviceDetail/qiang.png b/static/images/6155/DeviceDetail/qiang.png new file mode 100644 index 0000000..9be74d1 Binary files /dev/null and b/static/images/6155/DeviceDetail/qiang.png differ diff --git a/static/images/6155/DeviceDetail/remark.png b/static/images/6155/DeviceDetail/remark.png new file mode 100644 index 0000000..821f5e9 Binary files /dev/null and b/static/images/6155/DeviceDetail/remark.png differ diff --git a/static/images/6155/DeviceDetail/ruo.png b/static/images/6155/DeviceDetail/ruo.png new file mode 100644 index 0000000..5933bac Binary files /dev/null and b/static/images/6155/DeviceDetail/ruo.png differ diff --git a/static/images/6155/DeviceDetail/sendSucc.png b/static/images/6155/DeviceDetail/sendSucc.png new file mode 100644 index 0000000..a9cba80 Binary files /dev/null and b/static/images/6155/DeviceDetail/sendSucc.png differ diff --git a/static/images/6155/DeviceDetail/shan.png b/static/images/6155/DeviceDetail/shan.png new file mode 100644 index 0000000..ff4db45 Binary files /dev/null and b/static/images/6155/DeviceDetail/shan.png differ diff --git a/static/images/6155/DeviceDetail/slideToggle.png b/static/images/6155/DeviceDetail/slideToggle.png new file mode 100644 index 0000000..55d87ee Binary files /dev/null and b/static/images/6155/DeviceDetail/slideToggle.png differ diff --git a/static/images/6155/DeviceDetail/time.png b/static/images/6155/DeviceDetail/time.png new file mode 100644 index 0000000..68a4826 Binary files /dev/null and b/static/images/6155/DeviceDetail/time.png differ diff --git a/static/images/6155/DeviceDetail/uploadSuccess.png b/static/images/6155/DeviceDetail/uploadSuccess.png new file mode 100644 index 0000000..a0252a5 Binary files /dev/null and b/static/images/6155/DeviceDetail/uploadSuccess.png differ diff --git a/static/images/6155/DeviceDetail/video.png b/static/images/6155/DeviceDetail/video.png new file mode 100644 index 0000000..be64349 Binary files /dev/null and b/static/images/6155/DeviceDetail/video.png differ diff --git a/static/images/BLEAdd/device.png b/static/images/BLEAdd/device.png new file mode 100644 index 0000000..f3b9bc8 Binary files /dev/null and b/static/images/BLEAdd/device.png differ diff --git a/static/images/BLEAdd/linked.png b/static/images/BLEAdd/linked.png new file mode 100644 index 0000000..8801609 Binary files /dev/null and b/static/images/BLEAdd/linked.png differ diff --git a/static/images/BLEAdd/noLink.png b/static/images/BLEAdd/noLink.png new file mode 100644 index 0000000..b3af992 Binary files /dev/null and b/static/images/BLEAdd/noLink.png differ diff --git a/static/images/BLEAdd/wifi.png b/static/images/BLEAdd/wifi.png new file mode 100644 index 0000000..e8eda14 Binary files /dev/null and b/static/images/BLEAdd/wifi.png differ diff --git a/store/BLETools.js b/store/BLETools.js index 8e8b4a6..5e291c5 100644 --- a/store/BLETools.js +++ b/store/BLETools.js @@ -20,7 +20,7 @@ let connected = false //测试 let service_uuid = "0000AE30-0000-1000-8000-00805F9B34FB" -let write_characteristic = "0000AE03-0000-1000-8000-00805F9B34FB" +let write_characteristic = "0000AE03-0000-1000-8000-00805F9B34FB" let notify_characteristic = "0000AE03-0000-1000-8000-00805F9B34FB" let notify_characteristic_2 = "0000AE02-0000-1000-8000-00805F9B34FB"//获取设备电量和设备mac地址 @@ -123,15 +123,18 @@ String.prototype.transFloat = function() { return str.indexOf('.') != -1 ? parseFloat(str).toFixed(1) : str } -// //uni -uni.onBluetoothAdapterStateChange(function(res) { - if (!res.available) { - isOpen = false - isBleOn = false - } else { - isBleOn = true - } -}) +// + +if (uni.getSystemInfoSync().platform){ + uni.onBluetoothAdapterStateChange(function(res) { + if (!res.available) { + isOpen = false + isBleOn = false + } else { + isBleOn = true + } + }) +} diff --git a/uni_modules/qf-image-cropper/changelog.md b/uni_modules/qf-image-cropper/changelog.md new file mode 100644 index 0000000..531a5e4 --- /dev/null +++ b/uni_modules/qf-image-cropper/changelog.md @@ -0,0 +1,67 @@ +## 2.2.4(2024-06-21) +* 新增 reverseRotatable 属性,是否支持逆向翻转 +* 修复 `2.1.7` 版本导致旋转后图片没有自动适配裁剪框的问题 +## 2.2.3(2024-06-21) +* 新增 gpu 属性,是否开启硬件加速,图片缩放过程中如果出现元素的“留影”或“重影”效果,可通过该方式解决或减轻这一问题 +* 修复 组件使用 `v-if` 并设置 `src` 属性时可能会出现图片渲染位置存在偏差的问题 + +## 2.2.2(2024-06-21) +* 优化 组件实例 chooseImage 方法支持传参 +* 修复 组件使用 `v-if` 时组件无非正常渲染的问题 + +## 2.2.1(2024-06-15) +* 修复 H5平台不支持手势拖动图片的问题 + +## 2.2.0(2024-05-31) +* 修复 APP平台 `vue2` 项目因 `2.1.9` 版本修复 `vue3` 项目bug而引发的问题 + +## 2.1.9(2024-05-29) +* 修复 APP平台 `vue3` 项目因 uniapp `renderjs` 中未支持条件编译,导致运行了H5平台代码报错的问题 + +## 2.1.8(2024-05-29) +* 新增 zIndex 属性,调整组件层级 +* 新增 组件内容插槽 +* 优化 微信小程序平台动态修改元素style时的多余内容 + +## 2.1.7(2024-05-28) +* 新增 checkRange 属性,当 checkRange=false 时允许图片位置超出裁剪边界 +* 新增 minScale 属性,图片最小缩放倍数,当 minScale<0 时可使图片宽高不再受裁剪区域宽高限制 +* 新增 backgroundColor 属性,生成图片背景色,如果裁剪区域没有完全包含在图片中时,不设置该属性生成图片存在一定的透明块 +* 优化 动态修改图片宽高但没有传入src时,尺寸适应问题 +* 修复 APP平台通过 `this.$ownerInstance` 获取组件实例时机过早,其值为 `undefined` 导致报错界面没有正常渲染的问题 + +## 2.1.6(2023-04-16) +* 修复 组件使用 v-show 指令会导致选择图片后初始位置严重偏位的问题 + +## 2.1.5(2023-04-15) +* 新增 兼容APP平台 + +## 2.1.4(2023-03-13) +* 新增 fileType 属性,用于指定生成文件的类型,只支持 'jpg' 或 'png',默认为 'png' +* 新增 delay 属性,微信小程序平台使用 `Canvas 2D` 绘制时控制图片从绘制到生成所需时间 +* 优化 当生成图片的尺寸宽/高超过 Canvas 2D 最大限制(1365*1365)则将画布尺寸缩放在限制范围内绘制完成后输出目标尺寸 +* 优化 旋转图标指示方向与实际旋转方向不符 + +## 2.1.3(2023-02-06) +* 优化 vue3支持 + +## 2.1.2(2023-02-03) +* 新增 navigation 属性,H5平台当 showAngle 为 true 时,使用插件的页面在 `page.json` 中配置了 "navigationStyle": "custom" 时,必须将此值设为 false ,否则四个可拉伸角的触发位置会有偏差 +* 修复 H5平台部分设备(已知iPhone11以下机型)拍照的图片缩放时会闪动的问题 + +## 2.1.1(2022-12-06) +* 修复 横屏适配问题 + +## 2.1.0(2022-12-06) +* 新增 兼容H5平台,使用 renderjs 响应手势事件 + +## 2.0.0(2022-12-05) +* 重构 插件,使用 WXS 响应手势事件 +* 新增 图片翻转 +* 新增 拉伸裁剪框放大图片 +* 新增 监听PC鼠标滚轮触发缩放 +* 新增 圆形、圆角矩形的图片裁剪 +* 优化 图片缩放,移动端以双指触摸中心点为缩放中心点,PC端以鼠标所在点为缩放中心点 +* 优化 裁剪框样式 +* 优化 图片位置拖动 支持边界回弹效果(滑动时可滑出边界,释放时回弹到边界) +* 优化 生成图片使用新版 Canvas 2D 接口 diff --git a/uni_modules/qf-image-cropper/components/qf-image-cropper/qf-image-cropper.render.js b/uni_modules/qf-image-cropper/components/qf-image-cropper/qf-image-cropper.render.js new file mode 100644 index 0000000..d4e2339 --- /dev/null +++ b/uni_modules/qf-image-cropper/components/qf-image-cropper/qf-image-cropper.render.js @@ -0,0 +1,738 @@ +/** + * 图片编辑器-手势监听 + * 1. 支持编译到app-vue(uni-app 2.5.5及以上版本)、H5上 + */ +/** 图片偏移量 */ +var offset = { x: 0, y: 0 }; +/** 图片缩放比例 */ +var scale = 1; +/** 图片最小缩放比例 */ +var minScale = 1; +/** 图片旋转角度 */ +var rotate = 0; +/** 触摸点 */ +var touches = []; +/** 图片布局信息 */ +var img = {}; +/** 系统信息 */ +var sys = {}; +/** 裁剪区域布局信息 */ +var area = {}; +/** 触摸行为类型 */ +var touchType = ''; +/** 操作角的位置 */ +var activeAngle = 0; +/** 裁剪区域布局信息偏移量 */ +var areaOffset = { left: 0, right: 0, top: 0, bottom: 0 }; +/** 元素ID */ +var elIds = { + 'imageStyles': 'crop-image', + 'maskStylesList': 'crop-mask-block', + 'borderStyles': 'crop-border', + 'circleBoxStyles': 'crop-circle-box', + 'circleStyles': 'crop-circle', + 'gridStylesList': 'crop-grid', + 'angleStylesList': 'crop-angle', +} +/** 记录上次初始化时间戳,排除APP重复更新 */ +var timestamp = 0; +/** vue3 renderjs 条件编译无效,以此方式区别 APP 和 H5 */ +// #ifdef H5 +var platform = 'H5'; +// #endif +// #ifdef APP +var platform = 'APP'; +// #endif +/** + * 样式对象转字符串 + * @param {Object} style 样式对象 + */ +function styleToString(style) { + if(typeof style === 'string') return style; + var str = ''; + for (let k in style) { + str += k + ':' + style[k] + ';'; + } + return str; +} +/** + * + * @param {Object} instance 页面实例对象 + * @param {Object} key 要修改样式的key + * @param {Object|Array} style 样式 + */ +function setStyle(instance, key, style) { + // console.log('setStyle', instance, key, JSON.stringify(style)) + // #ifdef APP-PLUS + if(platform === 'APP') { + if(Object.prototype.toString.call(style) === '[object Array]') { + for (var i = 0, len = style.length; i < len; i++) { + var el = window.document.getElementById(elIds[key] + '-' + (i + 1)); + el && (el.style = styleToString(style[i])); + } + } else { + var el = window.document.getElementById(elIds[key]); + el && (el.style = styleToString(style)); + } + } + // #endif + // #ifdef H5 + if(platform === 'H5') instance[key] = style; + // #endif +} +/** + * 触发页面实例指定方法 + * @param {Object} instance 页面实例对象 + * @param {Object} name 方法名称 + * @param {Object} obj 传递参数 + */ +function callMethod(instance, name, obj) { + // #ifdef APP-PLUS + if(platform === 'APP') instance.callMethod(name, obj); + // #endif + // #ifdef H5 + if(platform === 'H5') instance[name](obj); + // #endif +} +/** + * 计算两点间距 + * @param {Object} touches 触摸点信息 + */ +function getDistanceByTouches(touches) { + // 根据勾股定理求两点间距离 + var a = touches[1].pageX - touches[0].pageX; + var b = touches[1].pageY - touches[0].pageY; + var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)); + // 求两点间的中点坐标 + // 1. a、b可能为负值 + // 2. 在求a、b时,如用touches[1]减touches[0],则求中点坐标也得用touches[1]减a/2、b/2 + // 3. 同理,在求a、b时,也可用touches[0]减touches[1],则求中点坐标也得用touches[0]减a/2、b/2 + var x = touches[1].pageX - a / 2; + var y = touches[1].pageY - b / 2; + return { c, x, y }; +}; + +/** + * 修正取值 + * @param {Object} a + * @param {Object} b + * @param {Object} c + * @param {Object} reverse 是否反向 + */ +function correctValue(a, b, c, reverse) { + return reverse ? Math.max(Math.min(a, b), c) : Math.min(Math.max(a, b), c); +} + +/** + * 检查边界:限制 x、y 拖动范围,禁止滑出边界 + * @param {Object} e 点坐标 + */ +function checkRange(e) { + var r = rotate / 90 % 2; + if(r === 1) { // 因图片宽高可能不等,翻转 90° 或 270° 后图片宽高需反着计算,且左右和上下边界要根据差值做偏移 + var o = (img.height - img.width) / 2; // 宽高差值一半 + return { + x: correctValue(e.x, -img.height + o + area.width + area.left, area.left + o, img.height < area.height), + y: correctValue(e.y, -img.width - o + area.height + area.top, area.top - o, img.width < area.width) + } + } + return { + x: correctValue(e.x, -img.width + area.width + area.left, area.left, img.width < area.width), + y: correctValue(e.y, -img.height + area.height + area.top, area.top, img.height < area.height) + } +}; +/** + * 变更图片布局信息 + * @param {Object} e 布局信息 + */ +function changeImageRect(e) { + // console.log('changeImageRect', e) + offset.x += e.x || 0; + offset.y += e.y || 0; + if(e.check && area.checkRange) { // 检查边界 + var point = checkRange(offset); + if(offset.x !== point.x || offset.y !== point.y) { + offset = point; + } + } + + // 因频繁修改 width/height 会造成大量的内存消耗,改为scale + // e.instance.imageStyles = { + // width: img.width + 'px', + // height: img.height + 'px', + // transform: 'translate(' + (offset.x + ox) + 'px, ' + (offset.y + ox) + 'px) rotate(' + rotate +'deg)' + // }; + var ox = (img.width - img.oldWidth) / 2; + var oy = (img.height - img.oldHeight) / 2; + // e.instance.imageStyles = { + // width: img.oldWidth + 'px', + // height: img.oldHeight + 'px', + // transform: 'translate(' + (offset.x + ox) + 'px, ' + (offset.y + oy) + 'px) rotate(' + rotate +'deg) scale(' + scale + ')' + // }; + setStyle(e.instance, 'imageStyles', { + width: img.oldWidth + 'px', + height: img.oldHeight + 'px', + transform: (img.gpu ? 'translateZ(0) ' : '') + 'translate(' + (offset.x + ox) + 'px, ' + (offset.y + oy) + 'px' + ') rotate(' + rotate +'deg) scale(' + scale + ')' + }); + callMethod(e.instance, 'dataChange', { + width: img.width, + height: img.height, + x: offset.x, + y: offset.y, + rotate: rotate + }); +}; +/** + * 变更裁剪区域布局信息 + * @param {Object} e 布局信息 + */ +function changeAreaRect(e) { + // console.log('changeAreaRect', e) + // 变更蒙版样式 + setStyle(e.instance, 'maskStylesList', [ + { + left: 0, + width: (area.left + areaOffset.left) + 'px', + top: 0, + bottom: 0, + 'z-index': area.zIndex + 2 + }, + { + left: (area.right + areaOffset.right) + 'px', + right: 0, + top: 0, + bottom: 0, + 'z-index': area.zIndex + 2 + }, + { + left: (area.left + areaOffset.left) + 'px', + width: (area.width + areaOffset.right - areaOffset.left) + 'px', + top: 0, + height: (area.top + areaOffset.top) + 'px', + 'z-index': area.zIndex + 2 + }, + { + left: (area.left + areaOffset.left) + 'px', + width: (area.width + areaOffset.right - areaOffset.left) + 'px', + top: (area.bottom + areaOffset.bottom) + 'px', + // height: (area.top - areaOffset.bottom + sys.offsetBottom) + 'px', + bottom: 0, + 'z-index': area.zIndex + 2 + } + ]); + // 变更边框样式 + if(area.showBorder) { + setStyle(e.instance, 'borderStyles', { + left: (area.left + areaOffset.left) + 'px', + top: (area.top + areaOffset.top) + 'px', + width: (area.width + areaOffset.right - areaOffset.left) + 'px', + height: (area.height + areaOffset.bottom - areaOffset.top) + 'px', + 'z-index': area.zIndex + 3 + }); + } + + // 变更参考线样式 + if(area.showGrid) { + setStyle(e.instance, 'gridStylesList', [ + { + 'border-width': '1px 0 0 0', + left: (area.left + areaOffset.left) + 'px', + right: (area.right + areaOffset.right) + 'px', + top: (area.top + areaOffset.top + (area.height + areaOffset.bottom - areaOffset.top) / 3 - 0.5) + 'px', + width: (area.width + areaOffset.right - areaOffset.left) + 'px', + 'z-index': area.zIndex + 3 + }, + { + 'border-width': '1px 0 0 0', + left: (area.left + areaOffset.left) + 'px', + right: (area.right + areaOffset.right) + 'px', + top: (area.top + areaOffset.top + (area.height + areaOffset.bottom - areaOffset.top) * 2 / 3 - 0.5) + 'px', + width: (area.width + areaOffset.right - areaOffset.left) + 'px', + 'z-index': area.zIndex + 3 + }, + { + 'border-width': '0 1px 0 0', + top: (area.top + areaOffset.top) + 'px', + bottom: (area.bottom + areaOffset.bottom) + 'px', + left: (area.left + areaOffset.left + (area.width + areaOffset.right - areaOffset.left) / 3 - 0.5) + 'px', + height: (area.height + areaOffset.bottom - areaOffset.top) + 'px', + 'z-index': area.zIndex + 3 + }, + { + 'border-width': '0 1px 0 0', + top: (area.top + areaOffset.top) + 'px', + bottom: (area.bottom + areaOffset.bottom) + 'px', + left: (area.left + areaOffset.left + (area.width + areaOffset.right - areaOffset.left) * 2 / 3 - 0.5) + 'px', + height: (area.height + areaOffset.bottom - areaOffset.top) + 'px', + 'z-index': area.zIndex + 3 + } + ]); + } + + // 变更四个伸缩角样式 + if(area.showAngle) { + setStyle(e.instance, 'angleStylesList', [ + { + 'border-width': area.angleBorderWidth + 'px 0 0 ' + area.angleBorderWidth + 'px', + left: (area.left + areaOffset.left - area.angleBorderWidth) + 'px', + top: (area.top + areaOffset.top - area.angleBorderWidth) + 'px', + 'z-index': area.zIndex + 3 + }, + { + 'border-width': area.angleBorderWidth + 'px ' + area.angleBorderWidth + 'px 0 0', + left: (area.right + areaOffset.right - area.angleSize) + 'px', + top: (area.top + areaOffset.top - area.angleBorderWidth) + 'px', + 'z-index': area.zIndex + 3 + }, + { + 'border-width': '0 0 ' + area.angleBorderWidth + 'px ' + area.angleBorderWidth + 'px', + left: (area.left + areaOffset.left - area.angleBorderWidth) + 'px', + top: (area.bottom + areaOffset.bottom - area.angleSize) + 'px', + 'z-index': area.zIndex + 3 + }, + { + 'border-width': '0 ' + area.angleBorderWidth + 'px ' + area.angleBorderWidth + 'px 0', + left: (area.right + areaOffset.right - area.angleSize) + 'px', + top: (area.bottom + areaOffset.bottom - area.angleSize) + 'px', + 'z-index': area.zIndex + 3 + } + ]); + } + + // 变更圆角样式 + if(area.radius > 0) { + var radius = area.radius; + if(area.width === area.height && area.radius >= area.width / 2) { // 圆形 + radius = (area.width / 2); + } else { // 圆角矩形 + if(area.width !== area.height) { // 限制圆角半径不能超过短边的一半 + radius = Math.min(area.width / 2, area.height / 2, radius); + } + } + setStyle(e.instance, 'circleBoxStyles', { + left: (area.left + areaOffset.left) + 'px', + top: (area.top + areaOffset.top) + 'px', + width: (area.width + areaOffset.right - areaOffset.left) + 'px', + height: (area.height + areaOffset.bottom - areaOffset.top) + 'px', + 'z-index': area.zIndex + 2 + }); + setStyle(e.instance, 'circleStyles', { + 'box-shadow': '0 0 0 ' + Math.max(area.width, area.height) + 'px rgba(51, 51, 51, 0.8)', + 'border-radius': radius + 'px' + }); + } +}; +/** + * 缩放图片 + * @param {Object} e 布局信息 + */ +function scaleImage(e) { + // console.log('scaleImage', e) + var last = scale; + scale = Math.min(Math.max(e.scale + scale, minScale), img.maxScale); + if(last !== scale) { + img.width = img.oldWidth * scale; + img.height = img.oldHeight * scale; + // 参考问题:有一个长4000px、宽4000px的四方形ABCD,A点的坐标固定在(-2000,-2000), + // 该四边形上有一个点E,坐标为(-100,-300),将该四方形复制一份并缩小到90%后, + // 新四边形的A点坐标为多少时可使新四边形的E点与原四边形的E点重合? + // 预期效果:从图中选取某点(参照物)为中心点进行缩放,缩放时无论图像怎么变化,该点位置始终固定不变 + // 计算方法:以相同起点先计算缩放前后两点间的距离,再加上原图像偏移量即可 + e.x = (e.x - offset.x) * (1 - scale / last); + e.y = (e.y - offset.y) * (1 - scale / last); + changeImageRect(e); + return true; + } + return false; +}; +/** + * 获取触摸点在哪个角 + * @param {number} x 触摸点x轴坐标 + * @param {number} y 触摸点y轴坐标 + * @return {number} 角的位置:0=无;1=左上;2=右上;3=左下;4=右下; + */ +function getToucheAngle(x, y) { + // console.log('getToucheAngle', x, y, JSON.stringify(area)) + var o = area.angleBorderWidth; // 需扩大触发范围则把 o 值加大即可 + var oy = sys.navigation ? 0 : sys.windowTop; + if(y >= area.top - o + oy && y <= area.top + area.angleSize + o + oy) { + if(x >= area.left - o && x <= area.left + area.angleSize + o) { + return 1; // 左上角 + } else if(x >= area.right - area.angleSize - o && x <= area.right + o) { + return 2; // 右上角 + } + } else if(y >= area.bottom - area.angleSize - o + oy && y <= area.bottom + o + oy) { + if(x >= area.left - o && x <= area.left + area.angleSize + o) { + return 3; // 左下角 + } else if(x >= area.right - area.angleSize - o && x <= area.right + o) { + return 4; // 右下角 + } + } + return 0; // 无触摸到角 +}; +/** + * 重置数据 + */ +function resetData() { + offset = { x: 0, y: 0 }; + scale = 1; + minScale = img.minScale; + rotate = 0; +}; +function getTouchs(touches) { + var result = []; + var len = touches ? touches.length : 0 + for (var i = 0; i < len; i++) { + result[i] = { + pageX: touches[i].pageX, + // h5无标题栏时,窗口顶部距离仍为标题栏高度,且触摸点y轴坐标还是有标题栏的值,即减去标题栏高度的值 + pageY: touches[i].pageY + sys.windowTop + }; + } + return result; +}; +var mouseEvent = false; +export default { + data() { + return { + imageStyles: {}, + maskStylesList: [{}, {}, {}, {}], + borderStyles: {}, + gridStylesList: [{}, {}, {}, {}], + angleStylesList: [{}, {}, {}, {}], + circleBoxStyles: {}, + circleStyles: {} + } + }, + created() { + // 监听 PC 端鼠标滚轮 + // #ifdef H5 + platform === 'H5' && window.addEventListener('mousewheel', async (e) => { + var touchs = getTouchs([e]) + img.src && scaleImage({ + instance: await this.getInstance(), + check: true, + // 鼠标向上滚动时,deltaY 固定 -100,鼠标向下滚动时,deltaY 固定 100 + scale: e.deltaY > 0 ? -0.05 : 0.05, + x: touchs[0].pageX, + y: touchs[0].pageY + }); + }); + // #endif + }, + // #ifdef H5 + mounted() { + platform === 'H5' && this.initH5Events(); + }, + // #endif + setPlatform(p) { + platform = p; + }, + methods: { + // #ifdef H5 + getTouchEvent(e) { + e.touches = [ + { pageX: e.pageX, pageY: e.pageY } + ]; + return e; + }, + initH5Events() { + const preview = document.getElementById('pic-preview'); + preview?.addEventListener('mousedown', (e, ev) => { + mouseEvent = true; + this.touchstart(this.getTouchEvent(e)); + }); + preview?.addEventListener('mousemove', (e) => { + if (!mouseEvent) return; + this.touchmove(this.getTouchEvent(e)); + }); + preview?.addEventListener('mouseup', (e) => { + mouseEvent = false; + this.touchend(this.getTouchEvent(e)) + }); + preview?.addEventListener('mouseleave', (e) => { + mouseEvent = false; + this.touchend(this.getTouchEvent(e)) + }); + }, + // #endif + async getInstance() { + // #ifdef APP-PLUS + if(platform === 'APP') + return this.$ownerInstance + ? Promise.resolve(this.$ownerInstance) + : new Promise((resolve) => { + setTimeout(async () => { + resolve(await this.getInstance()); + }); + }); + // #endif + // #ifdef H5 + if(platform === 'H5') + return Promise.resolve(this); + // #endif + }, + /** + * 初始化:观察数据变更 + * @param {Object} newVal 新数据 + * @param {Object} oldVal 旧数据 + * @param {Object} o 组件实例对象 + */ + initObserver: async function(newVal, oldVal, o, i) { + // console.log('initObserver', newVal, oldVal, o, i) + if(newVal && (!img.src || timestamp !== newVal.timestamp)) { + timestamp = newVal.timestamp; + img = newVal.img; + sys = newVal.sys; + area = newVal.area; + minScale = img.minScale; + resetData(); + const instance = await this.getInstance() + img.src && changeImageRect({ + instance, + x: (sys.windowWidth - img.width) / 2, + y: (sys.windowHeight + sys.windowTop - sys.offsetBottom - img.height) / 2 + }); + changeAreaRect({ + instance + }); + } + }, + /** + * 鼠标滚轮滚动 + * @param {Object} e 事件对象 + * @param {Object} o 组件实例对象 + */ + mousewheel: function(e, o) { + // h5平台 wheel 事件无法判断滚轮滑动方向,需使用 mousewheel + }, + /** + * 触摸开始 + * @param {Object} e 事件对象 + * @param {Object} o 组件实例对象 + */ + touchstart: function(e, o) { + if(!img.src) return; + touches = getTouchs(e.touches); + activeAngle = area.showAngle ? getToucheAngle(touches[0].pageX, touches[0].pageY) : 0; + if(touches.length === 1 && activeAngle !== 0) { + touchType = 'stretch'; // 伸缩裁剪区域 + } else { + touchType = ''; + } + // console.log('touchstart', e, activeAngle) + }, + /** + * 触摸移动 + * @param {Object} e 事件对象 + * @param {Object} o 组件实例对象 + */ + touchmove: async function(e, o) { + if(!img.src) return; + // console.log('touchmove', e, o) + e.touches = getTouchs(e.touches); + if(touchType === 'stretch') { // 触摸四个角进行拉伸 + var point = e.touches[0]; + var start = touches[0]; + var x = point.pageX - start.pageX; + var y = point.pageY - start.pageY; + if(x !== 0 || y !== 0) { + var maxX = area.width * (1 - area.minScale); + var maxY = area.height * (1 - area.minScale); + // console.log(x, y, maxX, maxY, offset, area) + touches[0] = point; + switch(activeAngle) { + case 1: // 左上角 + x += areaOffset.left; + y += areaOffset.top; + // console.log(x, y, offset.left > area.left) + // console.log(maxX, maxY) + if(x >= 0 && y >= 0) { // 有效滑动 + var max = minScale < 1 && area.checkRange && ((offset.x > 0 && offset.x >= area.left) || (offset.y > 0 && offset.y >= area.top)) + ? Math.min(offset.y - area.top, offset.x - area.left) + : false; + if(x > y) { // 以x轴滑动距离为缩放基准 + if(typeof max === 'number') maxX = max; + if(x > maxX) x = maxX; + y = x * area.height / area.width; + } else { // 以y轴滑动距离为缩放基准 + if(typeof max === 'number') maxY = max; + if(y > maxY) y = maxY; + x = y * area.width / area.height; + } + areaOffset.left = x; + areaOffset.top = y; + } + break; + case 2: // 右上角 + x += areaOffset.right; + y += areaOffset.top; + if(x <= 0 && y >= 0) { // 有效滑动 + var max = minScale < 1 && area.checkRange && ((offset.x > 0 && offset.x + img.width <= area.right) || (offset.y > 0 && offset.y >= area.top)) + ? Math.min(offset.y - area.top, area.right - offset.x - img.width) + : false; + if(-x > y) { // 以x轴滑动距离为缩放基准 + if(typeof max === 'number') maxX = max; + if(-x > maxX) x = -maxX; + y = -x * area.height / area.width; + } else { // 以y轴滑动距离为缩放基准 + if(typeof max === 'number') maxY = max; + if(y > maxY) y = maxY; + x = -y * area.width / area.height; + } + areaOffset.right = x; + areaOffset.top = y; + } + break; + case 3: // 左下角 + x += areaOffset.left; + y += areaOffset.bottom; + if(x >= 0 && y <= 0) { // 有效滑动 + var max = minScale < 1 && area.checkRange && ((offset.x > 0 && offset.x >= area.left) || (offset.y > 0 && offset.y + img.height <= area.bottom)) + ? Math.min(area.bottom - offset.y - img.height, offset.x - area.left) + : false; + if(x > -y) { // 以x轴滑动距离为缩放基准 + if(typeof max === 'number') maxX = max; + if(x > maxX) x = maxX; + y = -x * area.height / area.width; + } else { // 以y轴滑动距离为缩放基准 + if(typeof max === 'number') maxY = max; + if(-y > maxY) y = -maxY; + x = -y * area.width / area.height; + } + areaOffset.left = x; + areaOffset.bottom = y; + } + break; + case 4: // 右下角 + x += areaOffset.right; + y += areaOffset.bottom; + if(x <= 0 && y <= 0) { // 有效滑动 + var max = minScale < 1 && area.checkRange && ((offset.x > 0 && offset.x + img.width <= area.right) || (offset.y > 0 && offset.y + img.height <= area.bottom)) + ? Math.min(area.bottom - offset.y - img.height, area.right - offset.x - img.width) + : false; + if(-x > -y) { // 以x轴滑动距离为缩放基准 + if(typeof max === 'number') maxX = max; + if(-x > maxX) x = -maxX; + y = x * area.height / area.width; + } else { // 以y轴滑动距离为缩放基准 + if(typeof max === 'number') maxY = max; + if(-y > maxY) y = -maxY; + x = y * area.width / area.height; + } + areaOffset.right = x; + areaOffset.bottom = y; + } + break; + } + // console.log(x, y, JSON.stringify(areaOffset)) + changeAreaRect({ + instance: await this.getInstance(), + }); + // this.draw(); + } + } else if (e.touches.length == 2) { // 双点触摸缩放 + var start = getDistanceByTouches(touches); + var end = getDistanceByTouches(e.touches); + scaleImage({ + instance: await this.getInstance(), + check: !area.bounce, + scale: (end.c - start.c) / 100, + x: end.x, + y: end.y + }); + touchType = 'scale'; + } else if(touchType === 'scale') {// 从双点触摸变成单点触摸 / 从缩放变成拖动 + touchType = 'move'; + } else { + changeImageRect({ + instance: await this.getInstance(), + check: !area.bounce, + x: e.touches[0].pageX - touches[0].pageX, + y: e.touches[0].pageY - touches[0].pageY + }); + touchType = 'move'; + } + touches = e.touches; + }, + /** + * 触摸结束 + * @param {Object} e 事件对象 + * @param {Object} o 组件实例对象 + */ + touchend: async function(e, o) { + if(!img.src) return; + if(touchType === 'stretch') { // 拉伸裁剪区域的四个角缩放 + // 裁剪区域宽度被缩放到多少 + var left = areaOffset.left; + var right = areaOffset.right; + var top = areaOffset.top; + var bottom = areaOffset.bottom; + var w = area.width + right - left; + var h = area.height + bottom - top; + // 图像放大倍数 + var p = scale * (area.width / w) - scale; + // 复原裁剪区域 + areaOffset = { left: 0, right: 0, top: 0, bottom: 0 }; + changeAreaRect({ + instance: await this.getInstance(), + }); + scaleImage({ + instance: await this.getInstance(), + scale: p, + x: area.left + left + (1 === activeAngle || 3 === activeAngle ? w : 0), + y: area.top + top + (1 === activeAngle || 2 === activeAngle ? h : 0) + }); + } else if (area.bounce) { // 检查边界并矫正,实现拖动到边界时有回弹效果 + changeImageRect({ + instance: await this.getInstance(), + check: true + }); + } + }, + /** + * 顺时针翻转图片90° + * @param {Object} e 事件对象 + * @param {Object} o 组件实例对象 + */ + rotateImage: async function(r) { + rotate = (rotate + (r || 90)) % 360; + + if(img.minScale >= 1) { + // 因图片宽高可能不等,翻转后图片宽高需足够填满裁剪区域 + minScale = 1; + if(img.width < area.height) { + minScale = area.height / img.oldWidth; + } else if(img.height < area.width) { + minScale = (area.width / img.oldHeight) + } + if(minScale !== 1) { + scaleImage({ + instance: await this.getInstance(), + scale: minScale - scale, + x: sys.windowWidth / 2, + y: (sys.windowHeight - sys.offsetBottom) / 2 + }); + } + } + + // 由于拖动画布后会导致图片位置偏移,翻转时的旋转中心点需是图片区域+偏移区域的中心点 + // 翻转x轴中心点 = (超出裁剪区域右侧的图片宽度 - 超出裁剪区域左侧的图片宽度) / 2 + // 翻转y轴中心点 = (超出裁剪区域下方的图片宽度 - 超出裁剪区域上方的图片宽度) / 2 + var ox = ((offset.x + img.width - area.right) - (area.left - offset.x)) / 2; + var oy = ((offset.y + img.height - area.bottom) - (area.top - offset.y)) / 2; + changeImageRect({ + instance: await this.getInstance(), + check: true, + x: -ox - oy, + y: -oy + ox + }); + }, + rotateImage90: function() { + this.rotateImage(90) + }, + rotateImage270: function() { + this.rotateImage(270) + }, + } +} \ No newline at end of file diff --git a/uni_modules/qf-image-cropper/components/qf-image-cropper/qf-image-cropper.vue b/uni_modules/qf-image-cropper/components/qf-image-cropper/qf-image-cropper.vue new file mode 100644 index 0000000..80b1f74 --- /dev/null +++ b/uni_modules/qf-image-cropper/components/qf-image-cropper/qf-image-cropper.vue @@ -0,0 +1,746 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/uni_modules/qf-image-cropper/components/qf-image-cropper/qf-image-cropper.wxs b/uni_modules/qf-image-cropper/components/qf-image-cropper/qf-image-cropper.wxs new file mode 100644 index 0000000..27fbd51 --- /dev/null +++ b/uni_modules/qf-image-cropper/components/qf-image-cropper/qf-image-cropper.wxs @@ -0,0 +1,604 @@ +/** + * 图片编辑器-手势监听 + * 1. wxs 暂不支持 es6 语法 + * 2. 支持编译到微信小程序、QQ小程序、app-vue、H5上(uni-app 2.2.5及以上版本) + */ +/** 图片偏移量 */ +var offset = { x: 0, y: 0 }; +/** 图片缩放比例 */ +var scale = 1; +/** 图片最小缩放比例 */ +var minScale = 1; +/** 图片旋转角度 */ +var rotate = 0; +/** 触摸点 */ +var touches = []; +/** 图片布局信息 */ +var img = {}; +/** 系统信息 */ +var sys = {}; +/** 裁剪区域布局信息 */ +var area = {}; +/** 触摸行为类型 */ +var touchType = ''; +/** 操作角的位置 */ +var activeAngle = 0; +/** 裁剪区域布局信息偏移量 */ +var areaOffset = { left: 0, right: 0, top: 0, bottom: 0 }; +/** + * 计算两点间距 + * @param {Object} touches 触摸点信息 + */ +function getDistanceByTouches(touches) { + // 根据勾股定理求两点间距离 + var a = touches[1].pageX - touches[0].pageX; + var b = touches[1].pageY - touches[0].pageY; + var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)); + // 求两点间的中点坐标 + // 1. a、b可能为负值 + // 2. 在求a、b时,如用touches[1]减touches[0],则求中点坐标也得用touches[1]减a/2、b/2 + // 3. 同理,在求a、b时,也可用touches[0]减touches[1],则求中点坐标也得用touches[0]减a/2、b/2 + var x = touches[1].pageX - a / 2; + var y = touches[1].pageY - b / 2; + return { c, x, y }; +}; +/** + * 修正取值 + * @param {Object} a + * @param {Object} b + * @param {Object} c + * @param {Object} reverse 是否反向 + */ +function correctValue(a, b, c, reverse) { + return reverse ? Math.max(Math.min(a, b), c) : Math.min(Math.max(a, b), c); +} + +/** + * 检查边界:限制 x、y 拖动范围,禁止滑出边界 + * @param {Object} e 点坐标 + */ +function checkRange(e) { + var r = rotate / 90 % 2; + if(r === 1) { // 因图片宽高可能不等,翻转 90° 或 270° 后图片宽高需反着计算,且左右和上下边界要根据差值做偏移 + var o = (img.height - img.width) / 2; // 宽高差值一半 + return { + x: correctValue(e.x, -img.height + o + area.width + area.left, area.left + o, img.height < area.height), + y: correctValue(e.y, -img.width - o + area.height + area.top, area.top - o, img.width < area.width) + } + } + return { + x: correctValue(e.x, -img.width + area.width + area.left, area.left, img.width < area.width), + y: correctValue(e.y, -img.height + area.height + area.top, area.top, img.height < area.height) + } +}; +/** + * 变更图片布局信息 + * @param {Object} e 布局信息 + */ +function changeImageRect(e) { + offset.x += e.x || 0; + offset.y += e.y || 0; + var image = e.instance.selectComponent('.crop-image'); + if(e.check && area.checkRange) { // 检查边界 + var point = checkRange(offset); + if(offset.x !== point.x || offset.y !== point.y) { + offset = point; + } + } + // image.setStyle({ + // width: img.width + 'px', + // height: img.height + 'px', + // transform: 'translate(' + offset.x + 'px, ' + offset.y + 'px) rotate(' + rotate +'deg)' + // }); + var ox = (img.width - img.oldWidth) / 2; + var oy = (img.height - img.oldHeight) / 2; + image.setStyle({ + width: img.oldWidth + 'px', + height: img.oldHeight + 'px', + transform: (img.gpu ? 'translateZ(0) ' : '') + 'translate(' + (offset.x + ox) + 'px, ' + (offset.y + oy) + 'px) rotate(' + rotate +'deg) scale(' + scale + ')' + }); + + e.instance.callMethod('dataChange', { + width: img.width, + height: img.height, + x: offset.x, + y: offset.y, + rotate: rotate + }); +}; +/** + * 变更裁剪区域布局信息 + * @param {Object} e 布局信息 + */ +function changeAreaRect(e) { + // 变更蒙版样式 + var masks = e.instance.selectAllComponents('.crop-mask-block'); + var maskStyles = [ + { + left: 0, + width: (area.left + areaOffset.left) + 'px', + top: 0, + bottom: 0, + 'z-index': area.zIndex + 2 + }, + { + left: (area.right + areaOffset.right) + 'px', + right: 0, + top: 0, + bottom: 0, + 'z-index': area.zIndex + 2 + }, + { + left: (area.left + areaOffset.left) + 'px', + width: (area.width + areaOffset.right - areaOffset.left) + 'px', + top: 0, + height: (area.top + areaOffset.top) + 'px', + 'z-index': area.zIndex + 2 + }, + { + left: (area.left + areaOffset.left) + 'px', + width: (area.width + areaOffset.right - areaOffset.left) + 'px', + top: (area.bottom + areaOffset.bottom) + 'px', + // height: (area.top - areaOffset.bottom + sys.offsetBottom) + 'px', + bottom: 0, + 'z-index': area.zIndex + 2 + } + ]; + var len = masks.length; + for (var i = 0; i < len; i++) { + masks[i].setStyle(maskStyles[i]); + } + + // 变更边框样式 + if(area.showBorder) { + var border = e.instance.selectComponent('.crop-border'); + border.setStyle({ + left: (area.left + areaOffset.left) + 'px', + top: (area.top + areaOffset.top) + 'px', + width: (area.width + areaOffset.right - areaOffset.left) + 'px', + height: (area.height + areaOffset.bottom - areaOffset.top) + 'px', + 'z-index': area.zIndex + 3 + }); + } + + // 变更参考线样式 + if(area.showGrid) { + var grids = e.instance.selectAllComponents('.crop-grid'); + var gridStyles = [ + { + 'border-width': '1px 0 0 0', + left: (area.left + areaOffset.left) + 'px', + right: (area.right + areaOffset.right) + 'px', + top: (area.top + areaOffset.top + (area.height + areaOffset.bottom - areaOffset.top) / 3 - 0.5) + 'px', + width: (area.width + areaOffset.right - areaOffset.left) + 'px', + 'z-index': area.zIndex + 3 + }, + { + 'border-width': '1px 0 0 0', + left: (area.left + areaOffset.left) + 'px', + right: (area.right + areaOffset.right) + 'px', + top: (area.top + areaOffset.top + (area.height + areaOffset.bottom - areaOffset.top) * 2 / 3 - 0.5) + 'px', + width: (area.width + areaOffset.right - areaOffset.left) + 'px', + 'z-index': area.zIndex + 3 + }, + { + 'border-width': '0 1px 0 0', + top: (area.top + areaOffset.top) + 'px', + bottom: (area.bottom + areaOffset.bottom) + 'px', + left: (area.left + areaOffset.left + (area.width + areaOffset.right - areaOffset.left) / 3 - 0.5) + 'px', + height: (area.height + areaOffset.bottom - areaOffset.top) + 'px', + 'z-index': area.zIndex + 3 + }, + { + 'border-width': '0 1px 0 0', + top: (area.top + areaOffset.top) + 'px', + bottom: (area.bottom + areaOffset.bottom) + 'px', + left: (area.left + areaOffset.left + (area.width + areaOffset.right - areaOffset.left) * 2 / 3 - 0.5) + 'px', + height: (area.height + areaOffset.bottom - areaOffset.top) + 'px', + 'z-index': area.zIndex + 3 + } + ]; + var len = grids.length; + for (var i = 0; i < len; i++) { + grids[i].setStyle(gridStyles[i]); + } + } + + // 变更四个伸缩角样式 + if(area.showAngle) { + var angles = e.instance.selectAllComponents('.crop-angle'); + var angleStyles = [ + { + 'border-width': area.angleBorderWidth + 'px 0 0 ' + area.angleBorderWidth + 'px', + left: (area.left + areaOffset.left - area.angleBorderWidth) + 'px', + top: (area.top + areaOffset.top - area.angleBorderWidth) + 'px', + 'z-index': area.zIndex + 3 + }, + { + 'border-width': area.angleBorderWidth + 'px ' + area.angleBorderWidth + 'px 0 0', + left: (area.right + areaOffset.right - area.angleSize) + 'px', + top: (area.top + areaOffset.top - area.angleBorderWidth) + 'px', + 'z-index': area.zIndex + 3 + }, + { + 'border-width': '0 0 ' + area.angleBorderWidth + 'px ' + area.angleBorderWidth + 'px', + left: (area.left + areaOffset.left - area.angleBorderWidth) + 'px', + top: (area.bottom + areaOffset.bottom - area.angleSize) + 'px', + 'z-index': area.zIndex + 3 + }, + { + 'border-width': '0 ' + area.angleBorderWidth + 'px ' + area.angleBorderWidth + 'px 0', + left: (area.right + areaOffset.right - area.angleSize) + 'px', + top: (area.bottom + areaOffset.bottom - area.angleSize) + 'px', + 'z-index': area.zIndex + 3 + } + ]; + var len = angles.length; + for (var i = 0; i < len; i++) { + angles[i].setStyle(angleStyles[i]); + } + } + + // 变更圆角样式 + if(area.radius > 0) { + var circleBox = e.instance.selectComponent('.crop-circle-box'); + var circle = e.instance.selectComponent('.crop-circle'); + var radius = area.radius; + if(area.width === area.height && area.radius >= area.width / 2) { // 圆形 + radius = (area.width / 2); + } else { // 圆角矩形 + if(area.width !== area.height) { // 限制圆角半径不能超过短边的一半 + radius = Math.min(area.width / 2, area.height / 2, radius); + } + } + circleBox.setStyle({ + left: (area.left + areaOffset.left) + 'px', + top: (area.top + areaOffset.top) + 'px', + width: (area.width + areaOffset.right - areaOffset.left) + 'px', + height: (area.height + areaOffset.bottom - areaOffset.top) + 'px', + 'z-index': area.zIndex + 2 + }); + circle.setStyle({ + 'box-shadow': '0 0 0 ' + Math.max(area.width, area.height) + 'px rgba(51, 51, 51, 0.8)', + 'border-radius': radius + 'px' + }); + } +}; +/** + * 缩放图片 + * @param {Object} e 布局信息 + */ +function scaleImage(e) { + var last = scale; + scale = Math.min(Math.max(e.scale + scale, minScale), img.maxScale); + if(last !== scale) { + img.width = img.oldWidth * scale; + img.height = img.oldHeight * scale; + // 参考问题:有一个长4000px、宽4000px的四方形ABCD,A点的坐标固定在(-2000,-2000), + // 该四边形上有一个点E,坐标为(-100,-300),将该四方形复制一份并缩小到90%后, + // 新四边形的A点坐标为多少时可使新四边形的E点与原四边形的E点重合? + // 预期效果:从图中选取某点(参照物)为中心点进行缩放,缩放时无论图像怎么变化,该点位置始终固定不变 + // 计算方法:以相同起点先计算缩放前后两点间的距离,再加上原图像偏移量即可 + e.x = (e.x - offset.x) * (1 - scale / last); + e.y = (e.y - offset.y) * (1 - scale / last); + changeImageRect(e); + return true; + } + return false; +}; +/** + * 获取触摸点在哪个角 + * @param {number} x 触摸点x轴坐标 + * @param {number} y 触摸点y轴坐标 + * @return {number} 角的位置:0=无;1=左上;2=右上;3=左下;4=右下; + */ +function getToucheAngle(x, y) { + // console.log('getToucheAngle', x, y, JSON.stringify(area)) + var o = area.angleBorderWidth; // 需扩大触发范围则把 o 值加大即可 + if(y >= area.top - o && y <= area.top + area.angleSize + o) { + if(x >= area.left - o && x <= area.left + area.angleSize + o) { + return 1; // 左上角 + } else if(x >= area.right - area.angleSize - o && x <= area.right + o) { + return 2; // 右上角 + } + } else if(y >= area.bottom - area.angleSize - o && y <= area.bottom + o) { + if(x >= area.left - o && x <= area.left + area.angleSize + o) { + return 3; // 左下角 + } else if(x >= area.right - area.angleSize - o && x <= area.right + o) { + return 4; // 右下角 + } + } + return 0; // 无触摸到角 +}; +/** + * 重置数据 + */ +function resetData() { + offset = { x: 0, y: 0 }; + scale = 1; + minScale = img.minScale; + rotate = 0; +}; +/** +* 顺时针翻转图片90° +* @param {Object} e 事件对象 +* @param {Object} o 组件实例对象 +*/ +function rotateImage(e, o, r) { + rotate = (rotate + r) % 360; + + if(img.minScale >= 1) { + // 因图片宽高可能不等,翻转后图片宽高需足够填满裁剪区域 + minScale = 1; + if(img.width < area.height) { + minScale = area.height / img.oldWidth; + } else if(img.height < area.width) { + minScale = (area.width / img.oldHeight) + } + if(minScale !== 1) { + scaleImage({ + instance: o, + scale: minScale - scale, + x: sys.windowWidth / 2, + y: (sys.windowHeight - sys.offsetBottom) / 2 + }); + } + } + + // 由于拖动画布后会导致图片位置偏移,翻转时的旋转中心点需是图片区域+偏移区域的中心点 + // 翻转x轴中心点 = (超出裁剪区域右侧的图片宽度 - 超出裁剪区域左侧的图片宽度) / 2 + // 翻转y轴中心点 = (超出裁剪区域下方的图片宽度 - 超出裁剪区域上方的图片宽度) / 2 + var ox = ((offset.x + img.width - area.right) - (area.left - offset.x)) / 2; + var oy = ((offset.y + img.height - area.bottom) - (area.top - offset.y)) / 2; + changeImageRect({ + instance: o, + check: true, + x: -ox - oy, + y: -oy + ox + }); +}; +module.exports = { + /** + * 初始化:观察数据变更 + * @param {Object} newVal 新数据 + * @param {Object} oldVal 旧数据 + * @param {Object} o 组件实例对象 + */ + initObserver: function(newVal, oldVal, o, i) { + if(newVal) { + img = newVal.img; + sys = newVal.sys; + area = newVal.area; + minScale = img.minScale; + resetData(); + img.src && changeImageRect({ + instance: o, + x: (sys.windowWidth - img.width) / 2, + y: (sys.windowHeight - sys.offsetBottom - img.height) / 2 + }); + changeAreaRect({ + instance: o + }); + // console.log('initRect', JSON.stringify(newVal)) + } + }, + /** + * 鼠标滚轮滚动 + * @param {Object} e 事件对象 + * @param {Object} o 组件实例对象 + */ + mousewheel: function(e, o) { + if(!img.src) return; + scaleImage({ + instance: o, + check: true, + // 鼠标向上滚动时,deltaY 固定 -100,鼠标向下滚动时,deltaY 固定 100 + scale: e.detail.deltaY > 0 ? -0.05 : 0.05, + x: e.touches[0].pageX, + y: e.touches[0].pageY + }); + }, + /** + * 触摸开始 + * @param {Object} e 事件对象 + * @param {Object} o 组件实例对象 + */ + touchstart: function(e, o) { + if(!img.src) return; + touches = e.touches; + activeAngle = area.showAngle ? getToucheAngle(touches[0].pageX, touches[0].pageY) : 0; + if(touches.length === 1 && activeAngle !== 0) { + touchType = 'stretch'; // 伸缩裁剪区域 + } else { + touchType = ''; + } + // console.log('touchstart', JSON.stringify(e), activeAngle) + }, + /** + * 触摸移动 + * @param {Object} e 事件对象 + * @param {Object} o 组件实例对象 + */ + touchmove: function(e, o) { + if(!img.src) return; + // console.log('touchmove', JSON.stringify(e), JSON.stringify(o)) + if(touchType === 'stretch') { // 触摸四个角进行拉伸 + var point = e.touches[0]; + var start = touches[0]; + var x = point.pageX - start.pageX; + var y = point.pageY - start.pageY; + if(x !== 0 || y !== 0) { + var maxX = area.width * (1 - area.minScale); + var maxY = area.height * (1 - area.minScale); + // console.log(x, y, maxX, maxY, offset, area) + touches[0] = point; + switch(activeAngle) { + case 1: // 左上角 + x += areaOffset.left; + y += areaOffset.top; + if(x >= 0 && y >= 0) { // 有效滑动 + var max = minScale < 1 && area.checkRange && ((offset.x > 0 && offset.x >= area.left) || (offset.y > 0 && offset.y >= area.top)) + ? Math.min(offset.y - area.top, offset.x - area.left) + : false; + if(x > y) { // 以x轴滑动距离为缩放基准 + if(typeof max === 'number') maxX = max; + if(x > maxX) x = maxX; + y = x * area.height / area.width; + } else { // 以y轴滑动距离为缩放基准 + if(typeof max === 'number') maxY = max; + if(y > maxY) y = maxY; + x = y * area.width / area.height; + } + areaOffset.left = x; + areaOffset.top = y; + } + break; + case 2: // 右上角 + x += areaOffset.right; + y += areaOffset.top; + if(x <= 0 && y >= 0) { // 有效滑动 + var max = minScale < 1 && area.checkRange && ((offset.x > 0 && offset.x + img.width <= area.right) || (offset.y > 0 && offset.y >= area.top)) + ? Math.min(offset.y - area.top, area.right - offset.x - img.width) + : false; + if(-x > y) { // 以x轴滑动距离为缩放基准 + if(typeof max === 'number') maxX = max; + if(-x > maxX) x = -maxX; + y = -x * area.height / area.width; + } else { // 以y轴滑动距离为缩放基准 + if(typeof max === 'number') maxY = max; + if(y > maxY) y = maxY; + x = -y * area.width / area.height; + } + areaOffset.right = x; + areaOffset.top = y; + } + break; + case 3: // 左下角 + x += areaOffset.left; + y += areaOffset.bottom; + if(x >= 0 && y <= 0) { // 有效滑动 + var max = minScale < 1 && area.checkRange && ((offset.x > 0 && offset.x >= area.left) || (offset.y > 0 && offset.y + img.height <= area.bottom)) + ? Math.min(area.bottom - offset.y - img.height, offset.x - area.left) + : false; + if(x > -y) { // 以x轴滑动距离为缩放基准 + if(typeof max === 'number') maxX = max; + if(x > maxX) x = maxX; + y = -x * area.height / area.width; + } else { // 以y轴滑动距离为缩放基准 + if(typeof max === 'number') maxY = max; + if(-y > maxY) y = -maxY; + x = -y * area.width / area.height; + } + areaOffset.left = x; + areaOffset.bottom = y; + } + break; + case 4: // 右下角 + x += areaOffset.right; + y += areaOffset.bottom; + if(x <= 0 && y <= 0) { // 有效滑动 + var max = minScale < 1 && area.checkRange && ((offset.x > 0 && offset.x + img.width <= area.right) || (offset.y > 0 && offset.y + img.height <= area.bottom)) + ? Math.min(area.bottom - offset.y - img.height, area.right - offset.x - img.width) + : false; + if(-x > -y) { // 以x轴滑动距离为缩放基准 + if(typeof max === 'number') maxX = max; + if(-x > maxX) x = -maxX; + y = x * area.height / area.width; + } else { // 以y轴滑动距离为缩放基准 + if(typeof max === 'number') maxY = max; + if(-y > maxY) y = -maxY; + x = y * area.width / area.height; + } + areaOffset.right = x; + areaOffset.bottom = y; + } + break; + } + // console.log(x, y, JSON.stringify(areaOffset)) + changeAreaRect({ + instance: o, + }); + // this.draw(); + } + } else if (e.touches.length == 2) { // 双点触摸缩放 + var start = getDistanceByTouches(touches); + var end = getDistanceByTouches(e.touches); + scaleImage({ + instance: o, + check: !area.bounce, + scale: (end.c - start.c) / 100, + x: end.x, + y: end.y + }); + touchType = 'scale'; + } else if(touchType === 'scale') {// 从双点触摸变成单点触摸 / 从缩放变成拖动 + touchType = 'move'; + } else { + changeImageRect({ + instance: o, + check: !area.bounce, + x: e.touches[0].pageX - touches[0].pageX, + y: e.touches[0].pageY - touches[0].pageY + }); + touchType = 'move'; + } + touches = e.touches; + }, + /** + * 触摸结束 + * @param {Object} e 事件对象 + * @param {Object} o 组件实例对象 + */ + touchend: function(e, o) { + if(!img.src) return; + if(touchType === 'stretch') { // 拉伸裁剪区域的四个角缩放 + // 裁剪区域宽度被缩放到多少 + var left = areaOffset.left; + var right = areaOffset.right; + var top = areaOffset.top; + var bottom = areaOffset.bottom; + var w = area.width + right - left; + var h = area.height + bottom - top; + // 图像放大倍数 + var p = scale * (area.width / w) - scale; + // 复原裁剪区域 + areaOffset = { left: 0, right: 0, top: 0, bottom: 0 }; + changeAreaRect({ + instance: o, + }); + scaleImage({ + instance: o, + scale: p, + x: area.left + left + (1 === activeAngle || 3 === activeAngle ? w : 0), + y: area.top + top + (1 === activeAngle || 2 === activeAngle ? h : 0) + }); + } else if (area.bounce) { // 检查边界并矫正,实现拖动到边界时有回弹效果 + changeImageRect({ + instance: o, + check: true + }); + } + }, + /** + * 顺时针翻转图片90° + * @param {Object} e 事件对象 + * @param {Object} o 组件实例对象 + */ + rotateImage: function(e, o) { + rotateImage(e, o, 90); + }, + rotateImage90: function(e, o) { + rotateImage(e, o, 90) + }, + rotateImage270: function(e, o) { + rotateImage(e, o, 270) + }, + // 此处只用于对齐其他平台端的样式参数,防止异常,无作用 + imageStyles: '', + maskStylesList: ['', '', '', ''], + borderStyles: '', + gridStylesList: ['', '', '', ''], + angleStylesList: ['', '', '', ''], + circleBoxStyles: '', + circleStyles: '', +} \ No newline at end of file diff --git a/uni_modules/qf-image-cropper/package.json b/uni_modules/qf-image-cropper/package.json new file mode 100644 index 0000000..e945454 --- /dev/null +++ b/uni_modules/qf-image-cropper/package.json @@ -0,0 +1,81 @@ +{ + "id": "qf-image-cropper", + "displayName": "图片裁剪插件", + "version": "2.2.4", + "description": "图片裁剪插件,支持自定义尺寸、定点等比例缩放、拖动、图片翻转、剪切圆形/圆角图片、定制样式,功能多性能高体验好注释全。", + "keywords": [ + "qf-image-cropper", + "图片裁剪", + "图片编辑", + "头像裁剪", + "小程序" +], + "repository": "", + "engines": { + "HBuilderX": "^3.1.0" + }, +"dcloudext": { + "type": "component-vue", + "sale": { + "regular": { + "price": "0.00" + }, + "sourcecode": { + "price": "0.00" + } + }, + "contact": { + "qq": "" + }, + "declaration": { + "ads": "无", + "data": "插件不采集任何数据", + "permissions": "无" + }, + "npmurl": "" + }, + "uni_modules": { + "dependencies": [], + "encrypt": [], + "platforms": { + "client": { + "Vue": { + "vue2": "y", + "vue3": "y" + }, + "App": { + "app-vue": "y", + "app-nvue": "n" + }, + "H5-mobile": { + "Safari": "y", + "Android Browser": "y", + "微信浏览器(Android)": "y", + "QQ浏览器(Android)": "u" + }, + "H5-pc": { + "Chrome": "u", + "IE": "u", + "Edge": "u", + "Firefox": "u", + "Safari": "u" + }, + "小程序": { + "微信": "y", + "阿里": "n", + "百度": "n", + "字节跳动": "n", + "QQ": "u", + "钉钉": "n", + "快手": "n", + "飞书": "n", + "京东": "n" + }, + "快应用": { + "华为": "n", + "联盟": "n" + } + } + } + } +} \ No newline at end of file diff --git a/uni_modules/qf-image-cropper/readme.md b/uni_modules/qf-image-cropper/readme.md new file mode 100644 index 0000000..0c62aac --- /dev/null +++ b/uni_modules/qf-image-cropper/readme.md @@ -0,0 +1,95 @@ +# qf-image-cropper +## 图片裁剪插件 +uniapp微信小程序图片裁剪插件,支持自定义尺寸、定点等比例缩放、拖动、图片翻转、剪切圆形/圆角图片、定制样式,功能多性能高体验好注释全。 + +### 平台支持: +1. 支持微信小程序:移动端、PC端、开发者工具 +2. 支持H5平台(2.1.0版本起) +3. 支持APP平台(2.1.5版本起):Android、IOS +4. 其他平台暂未测试兼容性未知 + +### 支持功能: +1. 自定义裁剪尺寸 +2. 定点等比例缩放:移动端以双指触摸中心点为缩放中心点,PC端以鼠标所在点为缩放中心点 +3. 自由拖动:支持限制滑出边界,也支持回弹效果(滑动时可滑出边界,释放时回弹到边界) +4. 图片翻转:在裁剪尺寸非 1:1 的情况下,翻转时宽高无法铺满裁剪区域时,图片会自动放大到合适尺寸 +5. 裁剪生成新图片 +6. 本地选择图片 +7. 可定制样式:可自由选择是否渲染裁剪边框、可伸缩裁剪顶角、参考线 +8. 裁剪圆角图片:圆形、圆角矩形 + +### 属性说明 +| 属性名 | 类型 | 默认值 | 说明 | +|:---|:---|:---|:---| +| src | String | | 图片资源地址 | +| width | Number | 300 | 裁剪宽度 | +| height | Number | 300 | 裁剪高度 | +| showBorder | Boolean | true | 是否绘制裁剪区域边框 | +| showGrid | Boolean | true | 是否绘制裁剪区域网格参考线 | +| showAngle | Boolean | true | 是否展示四个支持伸缩的角 | +| areaScale | Number | 0.3 | 裁剪区域最小缩放倍数 | +| minScale | Number | 1 | 图片最小缩放倍数 | +| maxScale | Number | 5 | 图片最大缩放倍数 | +| checkRange | Boolean | true | 检查图片位置是否超出裁剪边界,如果超出则会矫正位置 | +| backgroundColor | String | | 生成图片背景色:如果裁剪区域没有完全包含在图片中时,不设置该属性则生成图片存在一定的透明块 | +| bounce | Boolean | true | 是否有回弹效果:当 checkRange 为 true 时有效,拖动时可以拖出边界,释放时会弹回边界 | +| rotatable | Boolean | true | 是否支持翻转 | +| reverseRotatable | Boolean | false | 是否支持逆向翻转 | +| choosable | Boolean | true | 是否支持从本地选择素材 | +| gpu | Boolean | false | 是否开启硬件加速,图片缩放过程中如果出现元素的“留影”或“重影”效果,可通过该方式解决或减轻这一问题 | +| angleSize | Number | 20 | 四个角尺寸,单位px | +| angleBorderWidth | Number | 2 | 四个角边框宽度,单位px | +| zIndex | Number/String | | 调整组件层级 | +| radius | Number | | 裁剪图片圆角半径,单位px | +| fileType | String | png | 生成文件的类型,只支持 'jpg' 或 'png'。默认为 'png' | +| delay | Number | 1000 | 图片从绘制到生成所需时间,单位ms
微信小程序平台使用 `Canvas 2D` 绘制时有效
如绘制大图或出现裁剪图片空白等情况应适当调大该值,因 `Canvas 2d` 采用同步绘制,需自己把控绘制完成时间 | +| navigation | Boolean | true | 页面是否是原生标题栏:
H5平台当 showAngle 为 true 时,使用插件的页面在 `page.json` 中配置了 `"navigationStyle": "custom"` 时,必须将此值设为 false ,否则四个可拉伸角的触发位置会有偏差。
注:因H5平台的窗口高度是包含标题栏的,而屏幕触摸点的坐标是不包含的 | +| @crop | EventHandle | | 剪裁完成后触发,event = { tempFilePath }。在H5平台下,tempFilePath 为 base64 | + +### 基本用法 +``` + + + +``` +通过ref组件实例可在进入页面后直接打开相册选择图片 +``` +mounted() { + this.$refs.qfImageCropper.chooseImage({ sourceType: ['album'] }); +} +``` +### 使用说明 +1.建议在`pages.json`中将引用插件的页面添加一下配置禁止下拉刷新和禁止页面滑动,防止出现性能或页面抖动等问题。 +``` +{ + "enablePullDownRefresh": false, + "disableScroll": true +} +``` +2.建议使用本插件不要设置过大宽高的目标图片尺寸,建议1365x1365以内,否则可能会导致如下问题: +``` +1.界面卡顿,内存占用过高 +2.生成图片失真(模糊) +3.确定裁剪后一直显示 `裁剪中...`,该问题是由 `uni.canvasToTempFilePath` 无法回调导致,不同平台不同设备限制可能有所不同。 +``` +3.如裁剪后的图片存在偏移的问题,请检查是否受自己项目中父组件或全局样式影响。 +4.src属性设置网络图片时,图片资源必须是能触发 `getImageInfo` API 的 success 回调才可用于插件裁剪。因此小程序平台获取网络图片信息需先配置download域名白名单才能生效。 \ No newline at end of file diff --git a/unpackage/dist/dev/.nvue/app.css.js b/unpackage/dist/dev/.nvue/app.css.js new file mode 100644 index 0000000..c5ba808 --- /dev/null +++ b/unpackage/dist/dev/.nvue/app.css.js @@ -0,0 +1,11 @@ +var __getOwnPropNames = Object.getOwnPropertyNames; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var require_app_css = __commonJS({ + "app.css.js"(exports) { + const _style_0 = {}; + exports.styles = [_style_0]; + } +}); +export default require_app_css(); diff --git a/unpackage/dist/dev/.nvue/app.js b/unpackage/dist/dev/.nvue/app.js new file mode 100644 index 0000000..8236d9e --- /dev/null +++ b/unpackage/dist/dev/.nvue/app.js @@ -0,0 +1,2 @@ +Promise.resolve("./app.css.js").then(() => { +}); diff --git a/unpackage/dist/dev/app-plus/__uniappautomator.js b/unpackage/dist/dev/app-plus/__uniappautomator.js new file mode 100644 index 0000000..0f9252f --- /dev/null +++ b/unpackage/dist/dev/app-plus/__uniappautomator.js @@ -0,0 +1,16 @@ +var n; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +function __spreadArrays(){for(var s=0,i=0,il=arguments.length;in;n++)r(e,e._deferreds[n]);e._deferreds=null}function c(e,n){var t=!1;try{e((function(e){t||(t=!0,i(n,e))}),(function(e){t||(t=!0,f(n,e))}))}catch(o){if(t)return;t=!0,f(n,o)}}var a=setTimeout;o.prototype.catch=function(e){return this.then(null,e)},o.prototype.then=function(e,n){var o=new this.constructor(t);return r(this,new function(e,n,t){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof n?n:null,this.promise=t}(e,n,o)),o},o.prototype.finally=e,o.all=function(e){return new o((function(t,o){function r(e,n){try{if(n&&("object"==typeof n||"function"==typeof n)){var u=n.then;if("function"==typeof u)return void u.call(n,(function(n){r(e,n)}),o)}i[e]=n,0==--f&&t(i)}catch(c){o(c)}}if(!n(e))return o(new TypeError("Promise.all accepts an array"));var i=Array.prototype.slice.call(e);if(0===i.length)return t([]);for(var f=i.length,u=0;i.length>u;u++)r(u,i[u])}))},o.resolve=function(e){return e&&"object"==typeof e&&e.constructor===o?e:new o((function(n){n(e)}))},o.reject=function(e){return new o((function(n,t){t(e)}))},o.race=function(e){return new o((function(t,r){if(!n(e))return r(new TypeError("Promise.race accepts an array"));for(var i=0,f=e.length;f>i;i++)o.resolve(e[i]).then(t,r)}))},o._immediateFn="function"==typeof setImmediate&&function(e){setImmediate(e)}||function(e){a(e,0)},o._unhandledRejectionFn=function(e){void 0!==console&&console&&console.warn("Possible Unhandled Promise Rejection:",e)};var l=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw Error("unable to locate global object")}();"Promise"in l?l.Promise.prototype.finally||(l.Promise.prototype.finally=e):l.Promise=o},"object"==typeof exports&&"undefined"!=typeof module?n():"function"==typeof define&&define.amd?define(n):n();var getRandomValues="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),rnds8=new Uint8Array(16);function rng(){if(!getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)}for(var byteToHex=[],i=0;i<256;++i)byteToHex[i]=(i+256).toString(16).substr(1);function v4(options,buf,offset){var i=buf&&offset||0;"string"==typeof options&&(buf="binary"===options?new Array(16):null,options=null);var rnds=(options=options||{}).random||(options.rng||rng)();if(rnds[6]=15&rnds[6]|64,rnds[8]=63&rnds[8]|128,buf)for(var ii=0;ii<16;++ii)buf[i+ii]=rnds[ii];return buf||function(buf,offset){var i=offset||0,bth=byteToHex;return[bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],"-",bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]]].join("")}(rnds)}var hasOwnProperty=Object.prototype.hasOwnProperty,isArray=Array.isArray,PATH_RE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;function getPaths(path,data){if(isArray(path))return path;if(data&&(val=data,key=path,hasOwnProperty.call(val,key)))return[path];var val,key,res=[];return path.replace(PATH_RE,(function(match,p1,offset,string){return res.push(offset?string.replace(/\\(\\)?/g,"$1"):p1||match),string})),res}function getDataByPath(data,path){var dataPath,paths=getPaths(path,data);for(dataPath=paths.shift();null!=dataPath;){if(null==(data=data[dataPath]))return;dataPath=paths.shift()}return data}var elementMap=new Map;function transEl(el){var _a;if(!function(el){if(el){var tagName=el.tagName;return 0===tagName.indexOf("UNI-")||"BODY"===tagName||0===tagName.indexOf("V-UNI-")||el.__isUniElement}return!1}(el))throw Error("no such element");var element,elementId,elem={elementId:(element=el,elementId=element._id,elementId||(elementId=v4(),element._id=elementId,elementMap.set(elementId,{id:elementId,element:element})),elementId),tagName:el.tagName.toLocaleLowerCase().replace("uni-","")};if(el.__vue__)(vm=el.__vue__)&&(vm.$parent&&vm.$parent.$el===el&&(vm=vm.$parent),vm&&!(null===(_a=vm.$options)||void 0===_a?void 0:_a.isReserved)&&(elem.nodeId=function(vm){if(vm._$weex)return vm._uid;if(vm._$id)return vm._$id;if(vm.uid)return vm.uid;var parent_1=function(vm){for(var parent=vm.$parent;parent;){if(parent._$id)return parent;parent=parent.$parent}}(vm);if(!vm.$parent)return"-1";var vnode=vm.$vnode,context=vnode.context;return context&&context!==parent_1&&context._$id?context._$id+";"+parent_1._$id+","+vnode.data.attrs._i:parent_1._$id+","+vnode.data.attrs._i}(vm)));else var vm;return"video"===elem.tagName&&(elem.videoId=elem.nodeId),elem}function getVm(el){return el.__vue__?{isVue3:!1,vm:el.__vue__}:{isVue3:!0,vm:el.__vueParentComponent}}function getScrollViewMain(el){var _a=getVm(el),isVue3=_a.isVue3,vm=_a.vm;return isVue3?vm.exposed.$getMain():vm.$refs.main}var FUNCTIONS={input:{input:function(el,value){var _a=getVm(el),isVue3=_a.isVue3,vm=_a.vm;isVue3?vm.exposed&&vm.exposed.$triggerInput({value:value}):(vm.valueSync=value,vm.$triggerInput({},{value:value}))}},textarea:{input:function(el,value){var _a=getVm(el),isVue3=_a.isVue3,vm=_a.vm;isVue3?vm.exposed&&vm.exposed.$triggerInput({value:value}):(vm.valueSync=value,vm.$triggerInput({},{value:value}))}},"scroll-view":{scrollTo:function(el,x,y){var main=getScrollViewMain(el);main.scrollLeft=x,main.scrollTop=y},scrollTop:function(el){return getScrollViewMain(el).scrollTop},scrollLeft:function(el){return getScrollViewMain(el).scrollLeft},scrollWidth:function(el){return getScrollViewMain(el).scrollWidth},scrollHeight:function(el){return getScrollViewMain(el).scrollHeight}},swiper:{swipeTo:function(el,index){el.__vue__.current=index}},"movable-view":{moveTo:function(el,x,y){el.__vue__._animationTo(x,y)}},switch:{tap:function(el){el.click()}},slider:{slideTo:function(el,value){var vm=el.__vue__,slider=vm.$refs["uni-slider"],offsetWidth=slider.offsetWidth,boxLeft=slider.getBoundingClientRect().left;vm.value=value,vm._onClick({x:(value-vm.min)*offsetWidth/(vm.max-vm.min)+boxLeft})}}};function createTouchList(touchInits){var _a,touches=touchInits.map((function(touch){return function(touch){if(document.createTouch)return document.createTouch(window,touch.target,touch.identifier,touch.pageX,touch.pageY,touch.screenX,touch.screenY,touch.clientX,touch.clientY);return new Touch(touch)}(touch)}));return document.createTouchList?(_a=document).createTouchList.apply(_a,touches):touches}var WebAdapter={getWindow:function(pageId){return window},getDocument:function(pageId){return document},getEl:function(elementId){var element=elementMap.get(elementId);if(!element)throw Error("element destroyed");return element.element},getOffset:function(node){var rect=node.getBoundingClientRect();return Promise.resolve({left:rect.left+window.pageXOffset,top:rect.top+window.pageYOffset})},querySelector:function(context,selector){return"page"===selector&&(selector="body"),Promise.resolve(transEl(context.querySelector(selector)))},querySelectorAll:function(context,selector){var elements=[],nodeList=document.querySelectorAll(selector);return[].forEach.call(nodeList,(function(node){try{elements.push(transEl(node))}catch(e){}})),Promise.resolve({elements:elements})},queryProperties:function(context,names){return Promise.resolve({properties:names.map((function(name){var value=getDataByPath(context,name.replace(/-([a-z])/g,(function(g){return g[1].toUpperCase()})));return"document.documentElement.scrollTop"===name&&0===value&&(value=getDataByPath(context,"document.body.scrollTop")),value}))})},queryAttributes:function(context,names){return Promise.resolve({attributes:names.map((function(name){return String(context.getAttribute(name))}))})},queryStyles:function(context,names){var style=getComputedStyle(context);return Promise.resolve({styles:names.map((function(name){return style[name]}))})},queryHTML:function(context,type){return Promise.resolve({html:(html="outer"===type?context.outerHTML:context.innerHTML,html.replace(/\n/g,"").replace(/(]*>)(]*>[^<]*<\/span>)(.*?<\/uni-text>)/g,"$1$3").replace(/<\/?[^>]*>/g,(function(replacement){return-1":""===replacement?"":0!==replacement.indexOf("0?xe:we)(e)},ke=Se,Ce=Math.min,Te=Se,Ae=Math.max,Me=Math.min,Ee=Z,Oe=function(e){return e>0?Ce(ke(e),9007199254740991):0},Le=function(e,t){return(e=Te(e))<0?Ae(e+t,0):Me(e,t)},ze=f("keys"),Ne=g,Ie=function(e){return ze[e]||(ze[e]=Ne(e))},Pe=J,De=Z,Be=(me=!1,function(e,t,n){var r,i=Ee(e),a=Oe(i.length),o=Le(n,a);if(me&&t!=t){for(;a>o;)if((r=i[o++])!=r)return!0}else for(;a>o;o++)if((me||o in i)&&i[o]===t)return me||o||0;return!me&&-1}),Re=Ie("IE_PROTO"),Fe="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),qe=function(e,t){var n,r=De(e),i=0,a=[];for(n in r)n!=Re&&Pe(r,n)&&a.push(n);for(;t.length>i;)Pe(r,n=t[i++])&&(~Be(a,n)||a.push(n));return a},je=Fe,Ve=Object.keys||function(e){return qe(e,je)},$e=k,He=A,We=Ve,Ue=E?Object.defineProperties:function(e,t){He(e);for(var n,r=We(t),i=r.length,a=0;i>a;)$e.f(e,n=r[a++],t[n]);return e};var Ye=A,Xe=Ue,Ze=Fe,Ge=Ie("IE_PROTO"),Ke=function(){},Je="prototype",Qe=function(){var e,t=O()("iframe"),n=Ze.length;for(t.style.display="none",function(){if(ye)return _e;ye=1;var e=l.document;return _e=e&&e.documentElement}().appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("