Commit 9adfef0f by 李伟康

Merge branch 'SAAS+V5.5.0' of http://192.168.3.233:8090/glsx/gl_tape into SAAS+V5.5.0

2 parents 65b039d6 788512b6
Showing 37 changed files with 1848 additions and 79 deletions
......@@ -2,7 +2,7 @@ import http from '../request/http'
module.exports = {
/**新建车损报价单 */
quotationAdd (data) {
quotationAdd(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.quotation.add',
projectName: 'boutique',
......@@ -10,7 +10,7 @@ module.exports = {
})
},
/** 报价单支付订单生成(带上签名)返回订单号(商户地址) */
quotationUpgrade (data) {
quotationUpgrade(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.quotation.pay.order.generate',
projectName: 'boutique',
......@@ -18,7 +18,7 @@ module.exports = {
})
},
// 校验订单是否需要上传合同协议
checkZyPayFlag (data) {
checkZyPayFlag(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.quotation.zyPayUrl.check',
projectName: 'boutique',
......@@ -27,7 +27,7 @@ module.exports = {
},
// 查询店铺配置
getShopMerchantPointConfig (data) {
getShopMerchantPointConfig(data) {
return http.post({
method: 'dj.api.smartcarlife.shopMerchantPointConfig.get',
projectName: 'boutique',
......@@ -36,7 +36,7 @@ module.exports = {
},
/** 查询报价单信息 */
getQuotationInfoById (data) {
getQuotationInfoById(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.quotation.find.by.id',
projectName: 'boutique',
......@@ -46,7 +46,7 @@ module.exports = {
/**
* 订单详情
*/
getOrderDetail (data) {
getOrderDetail(data) {
return http.post({
method: 'dj.api.smartcarlife.order.detail',
projectName: 'boutique',
......@@ -54,7 +54,7 @@ module.exports = {
})
},
/**pos支付 */
getPosQr (data) {
getPosQr(data) {
return http.post({
method: 'dj.api.smartcarlife.payOrder.create',
projectName: 'boutique',
......@@ -65,7 +65,7 @@ module.exports = {
* 查询门店录单设置
},
*/
orderSettingList (data) {
orderSettingList(data) {
return http.post({
method: 'dj.api.smartcarlife.order.field.setting.list',
projectName: 'boutique',
......@@ -74,7 +74,7 @@ module.exports = {
},
/** 报价单分页列表 */
quotationPage (data) {
quotationPage(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.quotation.page',
projectName: 'boutique',
......@@ -82,7 +82,7 @@ module.exports = {
})
},
/** 根据id查询报价单数据 */
getQuotationInfo (data) {
getQuotationInfo(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.quotation.generate',
projectName: 'boutique',
......@@ -90,7 +90,7 @@ module.exports = {
})
},
/** 修改车损报价单客户基本信息信息 */
updateCustomerInfo (data) {
updateCustomerInfo(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.quotation.customer.base.info.update',
projectName: 'boutique',
......@@ -99,7 +99,7 @@ module.exports = {
},
/** 报价单订单分状态统计信息 */
orderStatistics (data) {
orderStatistics(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.quotation.order.status.statistics',
projectName: 'boutique',
......@@ -107,7 +107,7 @@ module.exports = {
})
},
// 查询订单是否支持状态变更
getOrderRefundStep (data) {
getOrderRefundStep(data) {
return http.post({
method: 'dj.api.smartcarlife.refundApplyRecord.isExist',
projectName: 'boutique',
......@@ -115,7 +115,7 @@ module.exports = {
})
},
/**报价单-撤销工单 */
cancelOrderById (data) {
cancelOrderById(data) {
return http.post({
method: 'dj.api.smartcarlife.quotation.cancel',
projectName: 'boutique',
......@@ -123,7 +123,7 @@ module.exports = {
})
},
// 车损报价单战败订单创建
defeatOrderCreate (data) {
defeatOrderCreate(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.quotation.add.defeat.order',
projectName: 'boutique',
......@@ -131,7 +131,7 @@ module.exports = {
})
},
// 更新合同协议内容
updateZyInfo (data) {
updateZyInfo(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.quotation.zyPayUrl.update',
projectName: 'boutique',
......@@ -139,7 +139,7 @@ module.exports = {
})
},
/** 根据商户号商品id获取可选升级商品列表 */
quotationGoodsList (data) {
quotationGoodsList(data) {
return http.post({
method: 'dj.api.smartcarlife.quotationGoods.list',
projectName: 'boutique',
......@@ -148,14 +148,14 @@ module.exports = {
},
/**
* /** 修改车损报价单信息 */
updateQuotation (data) {
updateQuotation(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.quotation.update',
projectName: 'boutique',
...data
})
},
getCheckEmployeeList (data) {
getCheckEmployeeList(data) {
// 0->2.0 1->1.1 2->1.2 3->1.3 场景对应
// data.sceneList = [1]
return http.post({
......@@ -166,7 +166,7 @@ module.exports = {
// return api.post("dj.api.smartcarlife.employee.getByMerchantId", data);
},
/** 更新报价单状态 */
updateOrderStatus (data) {
updateOrderStatus(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.quotation.status.update',
projectName: 'boutique',
......@@ -178,11 +178,27 @@ module.exports = {
* 服务信息详情
*
*/
getServiceInfoDetail (data) {
getServiceInfoDetail(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.equityOrder.detail',
projectName: 'boutique',
...data
})
},
/** 权益单分页列表 */
equityPage(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.equityOrder.page',
projectName: 'boutique',
...data
})
},
/** 权益单统计信息 */
equityStatistics(data) {
return http.post({
method: 'dj.api.smartcarlife.vehicle.damage.upgrade.equityOrder.statics',
projectName: 'boutique',
...data
})
}
}
No preview for this file type
......@@ -3,12 +3,7 @@
<template v-if="entranceList.length">
<view class="entrance-container">
<view class="entrance-list">
<view
class="entrance-item"
v-for="(item, index) in entranceList"
:key="index"
@click="handleClick(item)"
>
<view class="entrance-item" v-for="(item, index) in entranceList" :key="index" @click="handleClick(item)">
<view :class="['sprite-icon', `icon-${item.icon}`]"></view>
<view class="entrance-name">{{ item.label }}</view>
</view>
......@@ -17,10 +12,7 @@
</template>
<template v-else>
<view class="developing flex">
<image
class="developing-icon"
src="../assets/images/common/developing.webp"
/>
<image class="developing-icon" src="../assets/images/common/developing.webp" />
功能开发中
</view>
</template>
......@@ -30,13 +22,11 @@
<script>
export default {
name: 'Entrance',
data () {
return {
}
data() {
return {}
},
computed: {
entranceList () {
entranceList() {
let { sceneType } = uni.$storage.get('userInfo'),
entranceList = [
{
......@@ -54,7 +44,7 @@ export default {
{
icon: 'equity-order',
label: '权益提单',
name: 'EquityOrder',
name: 'EquityManagement',
sceneType: [0]
},
{
......@@ -87,7 +77,7 @@ export default {
}
},
methods: {
handleClick (item) {
handleClick(item) {
// 这里可以根据实际需求进行跳转或功能处理
this.$emit('entranceClick', item)
}
......
......@@ -11,7 +11,7 @@
</view>
<view :class="['left-tabs', { three: tabs.length == 3 }]">
<template v-for="(i, index) in tabs">
<view :class="['tab-item', { tabActive: tabIndex == index }]" :key="index" @click="changeIndex(index, i)" v-if="!i.hidden">
<view :class="['tab-item', { tabActive: tabIndex == index }]" :key="index" @click="changeIndex(index, i)" v-if="!i.hidden && (i.name !== 'ActivityCenter' || activityTabVisible)">
<view class="icon-box">
<view :class="['sprite-icon', `icon-${i.icon}${tabIndex == index ? '-active' : ''}`]"></view>
</view>
......@@ -289,35 +289,38 @@ export default {
merchantId: shopMerchantId,
scene
}).then(result => {
console.log('有客户权限',result)
if (result) {
this.hasPerson = true
// this.activityTabVisible = scene !== 7
// this.tabs[this.tabs.length-1].hidden = scene !== 7
this.$nextTick(() => {
const activityTabIcon = document.querySelector('.sprite-icon.icon-activity')
if (activityTabIcon) {
const activityTab = activityTabIcon.closest('.tab-item')
if (activityTab) {
if (scene === 7) {
activityTab.style.display = 'none'
} else {
activityTab.style.display = 'block'
}
}
}
})
// this.$nextTick(() => {
// const activityTabIcon = document.querySelector('.sprite-icon.icon-activity')
// if (activityTabIcon) {
// const activityTab = activityTabIcon.closest('.tab-item')
// if (activityTab) {
// if (scene === 7) {
// activityTab.style.display = 'none'
// } else {
// activityTab.style.display = 'block'
// }
// }
// }
// })
this.activityTabVisible = scene !== 7;
} else {
// this.tabs[this.tabs.length-1].hidden = false
// this.activityTabVisible = false
this.$nextTick(() => {
const activityTabIcon = document.querySelector('.sprite-icon.icon-activity')
if (activityTabIcon) {
const activityTab = activityTabIcon.closest('.tab-item')
if (activityTab) {
activityTab.style.display = 'none'
}
}
})
// this.$nextTick(() => {
// const activityTabIcon = document.querySelector('.sprite-icon.icon-activity')
// if (activityTabIcon) {
// const activityTab = activityTabIcon.closest('.tab-item')
// if (activityTab) {
// activityTab.style.display = 'none'
// }
// }
// })
this.activityTabVisible = false;
}
})
},
......
......@@ -218,7 +218,7 @@ export default {
positionTypeList: [],
valueKey: '',
totalPrice: 0,
validateState:null,
validateState:true,
// 产品槽位配置,用于循环渲染产品组件
productSlots: {
frontGear: true,
......
......@@ -183,7 +183,7 @@ export default {
positionTypeList: [],
valueKey: '',
totalPrice: 0,
validateState:null,
validateState:true,
// 产品槽位配置,用于循环渲染产品组件
productSlots: {
frontGear: true,
......
......@@ -51,7 +51,7 @@ export default {
},
created() {
// 在组件创建时就开始监听,确保事件能被捕获
uni.$on('showExamSubmitPopup', () => {
uni.$on('showStudyPopup', () => {
console.log('接收到考试提交弹窗事件')
if (this.currentTab === 1) {
this.$refs.failedExam.showExamPopup = true
......@@ -62,7 +62,7 @@ export default {
},
beforeDestroy() {
// 组件销毁前移除监听
uni.$off('showExamSubmitPopup')
uni.$off('showStudyPopup')
},
mounted() {
this.getExamStatistics()
......
......@@ -147,6 +147,24 @@ module.exports = {
background: '#EAF1FF'
}
},
// 0待补单;2提单成功;3提单失败
equityStatus: {
2: {
text: '已完成',
color: '#2cca74',
background: '#eaf9f1'
},
0: {
text: '待补录',
color: '#F7A431',
background: '#FFF5E6'
},
3: {
text: '提单失败',
color: '#f24724',
background: '#fdece9'
}
},
// 订单状态 1 待跟进, 2 不升级, 3 待支付,4 已支付,6 已评价 , 9 已撤销
statusList: [
{
......
......@@ -203,7 +203,7 @@ export default {
popupTitle: '',
pointsMultiRole: 'Y',
formKey: Date.now(),
validateState: null
validateState: true
}
......
......@@ -159,6 +159,9 @@ export default {
this.searchObj = null
this.searchObj = val
console.log(this.searchObj)
if (!this.searchObj.orderStatus) {
this.tabIndex = 0
}
this.search()
},
copyText(e) {
......
......@@ -28,8 +28,6 @@
<upload-proof-of-payment @back="showUpload = false" @confirm="uploadConfirm" />
</view>
</template>
<!-- 支付弹框 -->
<OrderPay ref="OrderPay" @jumpSuccess="jumpSuccess" />
<NoticePopup ref="notice" title="重要提示" text="当前页面暂未保存,是否确认退出" type="warning"></NoticePopup>
</view>
</template>
......@@ -40,11 +38,7 @@ import utils from '@/utils/utils'
import GlCell from '../../../../components/Form/GlCell.vue'
import { UpdateOrderInfo, popupTypeEnum, payTypeList, titleList } from '../contant'
import { interceptionMixin } from '@/mixin/index'
import UploadProofOfPayment from './UploadProofOfPayment.vue'
import NoticePopup from '@/components/NoticePopup.vue'
import dayjs from 'dayjs'
import OrderPay from './OrderPay.vue'
import NP from 'number-precision'
export default {
name: 'CreateOrder',
......@@ -52,8 +46,7 @@ export default {
components: {
GlCell,
// OrderPopup,
UploadProofOfPayment,
OrderPay,
// UploadProofOfPayment,
NoticePopup
},
props: {
......
......@@ -25,7 +25,7 @@
</view>
<NoticePopup ref="notice" title="重要提示" text="当前页面暂未保存,是否确认退出" type="warning"></NoticePopup>
<!-- 学习中心权限弹窗 -->
<!-- 学习中心权限弹窗 -->
<StudyPopup :show.sync="showStudyPermissionPopup" title="" :width="848" :height="870" :topImage="require('@/assets/images/common/warning-notice.png')" :topImageWidth="848" :topImageHeight="248" style="overflow: hidden">
<StudyCenterPermissionPopup :lockReason="lockReason" @confirm="handleStudyPermissionConfirm" />
</StudyPopup>
......@@ -46,8 +46,10 @@ import { interceptionMixin } from '@/mixin/index'
import UpdateOrderInfo from './components/UpdateOrderInfo.vue'
import StudyPopup from '@/components/StudyPopup.vue'
import StudyCenterPermissionPopup from '@/components/StudyCenterPermissionPopup.vue'
import EquityManagement from './components/EquityManagement.vue'
import CreateEquity from './components/CreateEquity.vue'
import SignName from './components/SignName.vue'
export default {
mixins: [interceptionMixin],
......@@ -63,7 +65,9 @@ export default {
UpdateOrderInfo,
StudyPopup,
StudyCenterPermissionPopup,
CreateEquity
EquityManagement,
CreateEquity,
SignName
},
data() {
return {
......@@ -91,10 +95,10 @@ export default {
this.currentMonth = dayjs(currentDate).format('YYYY-MM')
},
async entranceClick(item) {
if(this.toolComponentName == item.name) return
if (this.toolComponentName == item.name) return
const noInterceptPage = ['DailyReport']
// if (!noInterceptPage.includes(item.name) && ((await this.checkDailyReport()) || (await this.inspectionOfProhibitionBill()))) return
if (!noInterceptPage.includes(item.name) && ((await this.checkDailyReport()))) return
if (!noInterceptPage.includes(item.name) && (await this.checkDailyReport())) return
// 提示去学习中心弹窗
const res = await this.getLimitRecord()
if (res.lockOrder) {
......
......@@ -556,7 +556,7 @@ export default {
uploadOtherFields: [{ key: 41, label: '其他图片', required: false, accept: 'image', maxCount: 30, fullwidth: true }],
currentField: null,
query: {},
validateVinState:null
validateState:true
}
},
onLoad(options) {
......
## 1.5.7(2025-11-24)
- fix: 修复uniappx 安卓打包报错问题
## 1.5.5(2025-09-18)
- fix: 修复uniappx 微信小程序 横屏时报错
## 1.5.4(2025-09-18)
- fix: 修复uniappx 微信小程序 删除离屏canvas报错
## 1.5.3(2025-08-31)
- feat: 兼容uniappx鸿蒙next
## 1.5.2(2025-04-01)
- fix: 修复`钉钉小程序`无法生成图片的问题
## 1.5.1(2025-03-28)
- fix: uniapp app 缺少,导致报错
## 1.5.0(2025-03-28)
- fix: uniappx 微信小程序的`landscape`报错
## 1.4.9(2025-03-27)
- fix: uniapp 缺少,导致报错
## 1.4.8(2025-03-26)
- fix: uniappx app `change`事件不生效的问题
## 1.4.7(2025-03-25)
- feat: 增加`change`事件
## 1.4.6(2024-07-18)
- chore: 更新文档
## 1.4.5(2024-07-17)
- chore: 删除多余console
## 1.4.4(2024-07-15)
- fix: 修复`钉钉小程序`无法生成图片的问题
## 1.4.3(2024-07-15)
- fix: 修复`钉钉小程序`无法使用的问题
## 1.4.2(2024-07-04)
- fix: 修复`vue2`因类型问题无法使用
## 1.4.1(2024-07-04)
- fix: 修复`uvue`因类型问题无法使用
## 1.4.0(2024-05-21)
- fix: 修复`nvue`因重复`width`和`height`重复导致无法使用
## 1.3.9(2024-04-11)
- feat: 增加`preferToDataURL`porps,是否优先使用`toDataURL`生成图片,在支持`toDataURL`的环境优先使用,会生成base64的图片
## 1.3.8(2024-04-10)
- fix: 修复因兼容抖音导致微信小程序图片不完整
## 1.3.7(2024-04-10)
- fix: 修复uniapp x(web)无法生图的问题
- feat: 支持uniapp x(web on pc)
## 1.3.6(2024-04-09)
- fix: 修复抖音小程序无法生成图片
## 1.3.5(2024-04-01)
- feat: 支持uniapp x ios(app-js)
## 1.3.4(2024-03-11)
- feat: app-vue,app-nvue支持生成图片时传`destWidth`,`destHeight`
## 1.3.3(2024-03-07)
- fix: 修复因小数导致mask无法生成
## 1.3.2(2024-03-06)
- fix: 修复app-vue多重复命名变量导致无法使用
## 1.3.1(2024-03-04)
- fix: 缺少this导致云打包失败
## 1.3.0(2024-02-28)
- feat: 支持uniapp x web
## 1.2.9(2024-02-21)
- fix: 修复微信小程序IOS会断断续续的问题
## 1.2.8(2023-12-21)
- fix: 修复redo函数漏了`,`
## 1.2.7(2023-12-19)
- fix: 修复因非uniapp x默认引入了uts文件,导入无法运行
## 1.2.6(2023-12-18)
- feat: 增加支持uniapp x
## 1.2.5(2023-10-11)
- fix: 修复PC浏览不生效的问题
## 1.2.4(2023-08-28)
- feat: 增加 `disabled`
## 1.2.3(2023-08-26)
- fix: 修复app-nvue 无法生成图片
## 1.2.2(2023-08-24)
- fix: 修复app端获取`boundingBox`尺寸异常
## 1.2.1(2023-08-23)
- fix: 修复因画板尺寸有小数导致`boundingBox`失效
## 1.2.0(2023-08-22)
- fix: vue3 app 无法在第一时间获取到 `getSystemInfoSync` 函数,故在生命周期里获取
## 1.1.9(2023-08-18)
- fix: 排除`backgroundColor`为`transparent`的参数,因为会导致生成空白图片
## 1.1.8(2023-08-16)
- chore: 去掉多余的console.log
## 1.1.7(2023-08-09)
- fix: 修复 支付宝无法生成的问题
## 1.1.6(2023-08-03)
- fix: 多了个 return
## 1.1.5(2023-07-27)
- fix: 修复 微信小程序PC端无法绘制问题
## 1.1.4(2023-07-21)
- fix: 修复 APP 报 `requestAnimationFrame` 的问题
## 1.1.3(2023-07-20)
- fix: 修复 性能较一般的手机 手写会卡顿的问题
## 1.1.2(2023-07-18)
- fix: 修复 非 canvas 2d 微信小程序 无法生成图片
## 1.1.1(2023-07-04)
- feat: 增加 `boundingBox` 属性,只生成有笔画的内容区域,从而缩小图片的尺寸节省空间
## 1.1.0(2023-06-20)
- feat: 增加 `canvasToTempFilePath` 质量参数
## 1.0.9(2023-06-13)
- fix: 修复大屏设备上,画板会被离屏canvas挡住的情况
## 1.0.8(2023-06-12)
- fix: 修复vue2 rendrejs 导入问题
## 1.0.7(2023-06-09)
- fix: 修复vue3 rendrejs 找到不节点问题
## 1.0.6(2023-05-23)
- chore: stylus 改为 scss
## 1.0.5(2023-05-16)
- fix: 修复转临时路径出错
## 1.0.4(2023-04-17)
- chore: 删除多余字符
## 1.0.3(2023-04-15)
- BUG: QQ小程序可以使用,会有报错但不影响使用
## 1.0.2(2023-04-15)
- feat: 支持横屏
- BUG: QQ小程序无法使用,为UNI官方问题,插件所需要的API传this都会报错。
## 1.0.1(2023-04-03)
- fix: 销毁时报错
## 1.0.0(2022-10-27)
- feat: 增加背景色
- feat: 修复 app canvasToTempFilePath 无操作只能执行一次的问题
## 0.8.0(2022-08-22)
- feat: 增加beforeDelay 延时初始化,可用于手写板在弹窗里时
## 0.7.0(2022-08-16)
- fix: 修复缺少 canvasWidth
## 0.6.0(2022-07-16)
- fix: 修复 success is no defined
## 0.5.0(2022-07-09)
- feat: canvasToTempFilePath success 增加返回 isEmpty
- fix: 修复 微信小程序 canvasToTempFilePath 无效问题
## 0.4.0(2022-07-04)
- fix: 生成图片缺少最后一笔
## 0.3.0(2022-05-24)
- chore: 支持多端 H5 小程序 APP APP-NVUE
## 0.2.0(2021-07-09)
- chore: 统一命名规范,无须主动引入组件
- fix: 修复错位问题
## 0.1.0(2021-03-07)
- 首次上传
- 撤消、清空、保存、模拟压感等功能
const uniPlatform = uni.getSystemInfoSync().uniPlatform
export const uniContext = (canvasId, context) => {
let ctx = uni.createCanvasContext(canvasId, context)
if (!ctx.uniDrawImage) {
ctx.uniDrawImage = ctx.drawImage
ctx.drawImage = (image, ...agrs) => {
ctx.uniDrawImage(image.src, ...agrs)
}
}
if (!ctx.getImageData) {
ctx.getImageData = (x, y, width, height) => {
return new Promise((resolve, reject) => {
// #ifdef MP || VUE2
if (context.proxy) context = context.proxy
// #endif
uni.canvasGetImageData({
canvasId,
x,
y,
width:parseInt(width),
height:parseInt(height),
success(res) {
resolve(res)
},
fail(error) {
reject(error)
}
}, context)
})
}
} else {
ctx._getImageData = ctx.getImageData
ctx.getImageData = (x, y, width, height) => {
return new Promise((resolve, reject) => {
ctx._getImageData({
x,
y,
width: parseInt(width) ,
height:parseInt(height),
success(res) {
resolve(res)
},
fail(error) {
reject(error)
}
})
})
}
}
return ctx
}
class Image {
constructor() {
this.currentSrc = null
this.naturalHeight = 0
this.naturalWidth = 0
this.width = 0
this.height = 0
this.tagName = 'IMG'
}
onerror() {}
onload() {}
set src(src) {
this.currentSrc = src
uni.getImageInfo({
src,
success: (res) => {
this.naturalWidth = this.width = res.width
this.naturalHeight = this.height = res.height
this.onload()
},
fail: () => {
this.onerror()
}
})
}
get src() {
return this.currentSrc
}
}
export const createImage = () => {
return new Image()
}
export function useCurrentPage() {
const pages = getCurrentPages();
return pages[pages.length - 1];
}
export const toDataURL = (canvasId, context, options = {}) => {
// #ifdef MP-QQ
// context = context.$scope
// #endif
// #ifdef MP-ALIPAY
context = ''
// #endif
return new Promise((resolve, reject) => {
let {
canvas,
width,
height,
destWidth = 0,
destHeight = 0,
x = 0,
y = 0,
preferToDataURL
} = options
const {
pixelRatio
} = uni.getSystemInfoSync()
// #ifdef MP-ALIPAY
const isDD = typeof dd != 'undefined'
if (!isDD && (!destWidth || !destHeight)) {
destWidth = width * pixelRatio;
destHeight = height * pixelRatio;
width = destWidth;
height = destHeight;
x = x * pixelRatio
y = y * pixelRatio
}
// #endif
const params = {
...options,
canvasId,
id: canvasId,
// #ifdef MP-ALIPAY
x,
y,
width,
height,
destWidth,
destHeight,
// #endif
canvas,
success: (res) => {
// 钉钉小程序 不存在tempFilePath
resolve(res.tempFilePath || res.filePath)
},
fail: (err) => {
reject(err)
}
}
// 抖音小程序canvas 2d不支持canvasToTempFilePath
if (canvas && canvas.toDataURL && preferToDataURL) {
let next = true
const devtools = uni.getSystemInfoSync().platform == 'devtools'
// #ifdef MP-TOUTIAO
next = uni.getSystemInfoSync().platform != 'devtools'
if (!next) {
console.warn('[lime-signature] 抖音开发工具不支持bbox')
}
// #endif
if ((x || y) && next) {
const offCanvas = uni.createOffscreenCanvas({
type: '2d'
});
const ctx = offCanvas.getContext("2d");
const destWidth = Math.floor(width * pixelRatio)
const destHeight = Math.floor(height * pixelRatio)
offCanvas.width = destWidth // canvas.width;
offCanvas.height = destHeight // canvas.height;
// ctx.scale(pixelRatio, pixelRatio)
// ctx.drawImage(canvas, Math.floor(x*pixelRatio), Math.floor(y*pixelRatio), destWidth, destHeight, 0,0, destWidth, destHeight);
// 抖音不能在drawImage使用canvas
const image = canvas.createImage()
image.onload = () => {
ctx.drawImage(image, Math.floor(x * pixelRatio), Math.floor(y * pixelRatio),
destWidth, destHeight, 0, 0, destWidth, destHeight)
const tempFilePath = offCanvas.toDataURL();
resolve(tempFilePath)
if (params.success) {
params.success({
tempFilePath
})
}
}
image.src = canvas.toDataURL()
} else {
const tempFilePath = canvas.toDataURL()
resolve(tempFilePath)
if (params.success) {
params.success({
tempFilePath
})
}
}
} else if (canvas && canvas.toTempFilePath) {
canvas.toTempFilePath(params)
} else {
uni.canvasToTempFilePath(params, context)
}
})
}
\ No newline at end of file
export default {
styles: String,
disableScroll: {
type: Boolean,
default: true
},
type: {
type: String,
default: '2d'
},
// 画笔颜色
penColor: {
type: String,
default: 'black'
},
penSize: {
type: Number,
default: 2
},
// 画板背景颜色
backgroundColor: String,
backgroundImage: String,
// 笔锋
openSmooth: Boolean,
// 画笔最小值
minLineWidth: {
type: Number,
default: 2
},
// 画笔最大值
maxLineWidth: {
type: Number,
default: 6
},
// 画笔达到最小宽度所需最小速度(px/ms),取值范围1.0-10.0,值越小,画笔越容易变细,笔锋效果会比较明显,可以自行调整查看效果,选出自己满意的值。
minSpeed: {
type: Number,
default: 1.5
},
// 相邻两线宽度增(减)量最大百分比,取值范围1-100,为了达到笔锋效果,画笔宽度会随画笔速度而改变,如果相邻两线宽度差太大,过渡效果就会很突兀,使用maxWidthDiffRate限制宽度差,让过渡效果更自然。可以自行调整查看效果,选出自己满意的值。
maxWidthDiffRate: {
type: Number,
default: 20
},
// 限制历史记录数,即最大可撤销数,传入0则关闭历史记录功能
maxHistoryLength: {
type: Number,
default: 20
},
beforeDelay: {
type: Number,
default: 0
},
landscape: {
type: Boolean
},
boundingBox: {
type: Boolean
},
disabled: {
type: Boolean
},
preferToDataURL: Boolean,
pixelRatio: Number
}
\ No newline at end of file
// #ifdef APP-VUE
// import { Signature } from '@signature'
import {
Signature
} from './signature.js'
import {
isTransparent
} from './utils'
export default {
data() {
return {
canvasid: null,
signature: null,
observer: null,
options: {},
saveCount: 0,
}
},
mounted() {
this.$nextTick(this.init)
},
methods: {
checkAndEmitEmptyStatus() {
setTimeout(()=>{
if (this.signature) {
const isEmpty = this.signature.isEmpty()
this.emit({
isEmpty
})
}
},0)
},
init() {
const el = this.$refs.limeSignature || this.$ownerInstance.$el;
this.canvas = document.createElement('canvas')
this.canvas.style = 'width: 100%; height: 100%;'
el.appendChild(this.canvas)
this.signature = new Signature({
el: this.canvas
})
this.signature.pen.setOption(this.options)
const width = this.signature.canvas.get('width')
const height = this.signature.canvas.get('height')
this.canvas?.addEventListener('touchend', this.checkAndEmitEmptyStatus.bind(this))
this.emit({
changeSize: {
width,
height
}
})
},
redo(v) {
if (v && this.signature) {
this.signature.redo()
this.checkAndEmitEmptyStatus()
}
},
undo(v) {
if (v && this.signature) {
this.signature.undo()
this.checkAndEmitEmptyStatus()
}
},
clear(v) {
if (v && this.signature) {
this.signature.clear()
this.checkAndEmitEmptyStatus()
}
},
destroy() {
if (this.canvas) {
this.canvas?.removeEventListener('touchend', this.checkAndEmitEmptyStatus.bind(this))
this.canvas.remove()
}
},
mask(param={}) {
if (this.signature) {
let {destWidth=0, destHeight=0} = JSON.parse(param)
let canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d');
const pixelRatio = this.signature.canvas.get('pixelRatio')
let width = this.signature.canvas.get('width')
let height = this.signature.canvas.get('height')
let context = this.signature.canvas.get('context')
canvas.width = width * pixelRatio
canvas.height = height * pixelRatio
const imageData = context.getImageData(0, 0, width * pixelRatio, height * pixelRatio);
for (let i = 0; i < imageData.data.length; i += 4) {
// 判断当前像素是否透明
const isTransparent = imageData.data[i + 3] === 0;
if (isTransparent) {
// 将透明像素设置为黑色背景
imageData.data[i] = 0;
imageData.data[i + 1] = 0;
imageData.data[i + 2] = 0;
} else {
// 将非透明像素设置为白色内容
imageData.data[i] = 255;
imageData.data[i + 1] = 255;
imageData.data[i + 2] = 255;
}
}
ctx.putImageData(imageData, 0, 0);
if(destWidth&&destHeight){
const _canvas = document.createElement('canvas')
_canvas.width = destWidth
_canvas.height = destHeight
const _context = _canvas.getContext('2d')
_context.drawImage(canvas, 0, 0, destWidth, destHeight)
canvas.remove()
canvas = _canvas
}
this.emit({
save: canvas.toDataURL()
})
canvas.remove()
}
},
save(param) {
let {
fileType = 'png',
quality = 1,
n,
destWidth = 0,
destHeight = 0,
} = JSON.parse(param)
const type = `image/${fileType}`.replace(/jpg/, 'jpeg');
if (n !== this.saveCount) {
this.saveCount = n;
const {
backgroundColor,
backgroundImage,
landscape,
boundingBox
} = this.options
const flag = landscape || backgroundColor || boundingBox||destWidth&&destHeight
const image = this.signature.canvas.get('el').toDataURL(!flag && type, !flag && quality)
if (flag) {
let canvas = document.createElement('canvas')
const pixelRatio = this.signature.canvas.get('pixelRatio')
let width = this.signature.canvas.get('width')
let height = this.signature.canvas.get('height')
let x = 0
let y = 0
const next = () => {
const size = [width, height]
if (landscape) {
size.reverse()
}
canvas.width = size[0] * pixelRatio
canvas.height = size[1] * pixelRatio
const param = [x, y, width, height, 0, 0, width, height].map(item => item * pixelRatio)
const context = canvas.getContext('2d')
if (landscape) {
context.translate(0, width * pixelRatio)
context.rotate(-Math.PI / 2)
}
if (backgroundColor && !isTransparent(backgroundColor)) {
context.fillStyle = backgroundColor
context.fillRect(0, 0, width * pixelRatio, height * pixelRatio)
}
const drawImage = () => {
// param
context.drawImage(this.signature.canvas.get('el'), ...param)
if(destWidth&&destHeight){
const _canvas = document.createElement('canvas')
_canvas.width = destWidth
_canvas.height = destHeight
const _context = _canvas.getContext('2d')
_context.drawImage(canvas, 0, 0, destWidth, destHeight)
canvas.remove()
canvas = _canvas
}
this.emit({
save: canvas.toDataURL(type, quality)
})
canvas.remove()
}
if (backgroundImage) {
const img = new Image();
img.onload = () => {
context.drawImage(img, ...param)
drawImage()
}
img.src = backgroundImage
}
if (!backgroundImage) {
drawImage()
}
}
if (boundingBox) {
const res = this.signature.getContentBoundingBox()
width = res.width
height = res.height
x = res.startX
y = res.startY
next()
} else {
next()
}
} else {
this.emit({
save: image
})
}
}
},
isEmpty(v) {
if (v && this.signature) {
const isEmpty = this.signature.isEmpty()
this.emit({
isEmpty
})
}
},
emit(event) {
this.$ownerInstance.callMethod('onMessage', {
detail: {
data: [{
event
}]
}
})
},
update(v) {
if (v) {
if (this.signature) {
this.options = v
this.signature.pen.setOption(v)
} else {
this.options = v
}
}
}
}
}
// #endif
\ No newline at end of file
// @ts-nocheck
import { LimeSignatureOptions, LimeSignaturePoint, LimeSignatureLine } from '../../index.uts'
let points : LimeSignatureLine = []
let undoStack : LimeSignatureLine[] = [];
let redoStack : LimeSignatureLine[] = [];
let lastX = 0;
let lastY = 0;
// #ifdef APP-ANDROID || APP-IOS
type SignatureUniElement = UniElement
type SignatureCanvasContext = DrawableContext
// #endif
// #ifdef APP-HARMONY
type SignatureUniElement = UniCanvasElement
type SignatureCanvasContext = CanvasRenderingContext2D
// #endif
export class Signature {
el : SignatureUniElement
ctx : SignatureCanvasContext
options : LimeSignatureOptions = {
penColor: 'black',
openSmooth: true,
disableScroll: true,
disabled: false,
penSize: 2,
minLineWidth: 2,
maxLineWidth: 6,
minSpeed: 1.5,
maxWidthDiffRate: 20,
maxHistoryLength: 20
} as LimeSignatureOptions
isEmpty : boolean = true
isDrawing : boolean = false
// historyList : LimeSignaturePoint[][] = []
// id : string
// instance : ComponentPublicInstance
touchstartCallbackWrapper: UniCallbackWrapper|null = null
touchmoveCallbackWrapper: UniCallbackWrapper|null= null
touchendCallbackWrapper: UniCallbackWrapper|null= null
change: ((isEmpty: boolean) => void)|null = null
constructor(el : SignatureUniElement) {
this.el = el
// #ifdef APP-ANDROID || APP-IOS
this.ctx = el.getDrawableContext() as DrawableContext
// #endif
// #ifdef APP-HARMONY
const dpr = uni.getDeviceInfo().devicePixelRatio ?? 1;
el.width = el.offsetWidth * dpr;
el.height = el.offsetHeight * dpr;
this.ctx = el.getContext('2d')
this.ctx.scale(dpr, dpr); // 仅需调用一次,当调用 reset 方法后需要再次 scale
// #endif
this.init()
}
onChange(cb: (isEmpty: boolean) => void){
this.change = cb
}
init() {
this.touchstartCallbackWrapper = this.el.addEventListener('touchstart', this.onTouchStart)
this.touchmoveCallbackWrapper = this.el.addEventListener('touchmove', this.onTouchMove)
this.touchendCallbackWrapper = this.el.addEventListener('touchend', this.onTouchEnd)
}
remove() {
if(this.touchstartCallbackWrapper == null) return
this.el.removeEventListener('touchstart', this.touchstartCallbackWrapper!)
this.el.removeEventListener('touchmove', this.touchmoveCallbackWrapper!)
this.el.removeEventListener('touchend', this.touchendCallbackWrapper!)
}
setOption(options : LimeSignatureOptions) {
this.options = options
}
disableScroll(event : UniTouchEvent) {
event.stopPropagation()
if (this.options.disableScroll) {
{
event.preventDefault()
}
}
}
getTouchLimeSignaturePoint(event : UniTouchEvent) : LimeSignaturePoint {
const rect = this.el.getBoundingClientRect()
const touche = event.touches[0];
const x = touche.clientX
const y = touche.clientY
// const force = touche.force
return {
x: x - rect.left,
y: y - rect.top
} as LimeSignaturePoint
}
onTouchStart: (event : UniTouchEvent) => void = (event : UniTouchEvent) =>{
if (this.options.disabled) {
return
}
this.disableScroll(event)
const { x, y } = this.getTouchLimeSignaturePoint(event)
this.isDrawing = true;
this.isEmpty = false
lastX = x
lastY = y
points.push({ x, y } as LimeSignaturePoint);
}
onTouchMove: (event : UniTouchEvent) => void = (event : UniTouchEvent) =>{
if (this.options.disabled || !this.isDrawing) {
return
}
this.disableScroll(event)
const { x, y } = this.getTouchLimeSignaturePoint(event)
const lineWidth = this.options.penSize
const strokeStyle = this.options.penColor
const point = { x, y } as LimeSignaturePoint
const last = { x: lastX, y: lastY } as LimeSignaturePoint
this.drawLine(point, last, lineWidth, strokeStyle)
lastX = x
lastY = y
points.push({ x, y, c: strokeStyle, w: lineWidth } as LimeSignaturePoint);
}
onTouchEnd: (event : UniTouchEvent) => void = (event : UniTouchEvent) =>{
this.disableScroll(event)
this.isDrawing = false;
undoStack.push(points);
redoStack = [] as LimeSignatureLine[];
points = [] as LimeSignaturePoint[];
this.change?.(this.isEmpty);
}
drawLine(point : LimeSignaturePoint, last : LimeSignaturePoint, lineWidth : number, strokeStyle : string) {
const ctx = this.ctx
ctx.lineWidth = lineWidth
ctx.strokeStyle = strokeStyle
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
ctx.beginPath()
ctx.moveTo(last.x, last.y)
ctx.lineTo(point.x, point.y)
ctx.stroke()
ctx.closePath()
// ctx.update()
this._draw()
}
_clear() {
// #ifdef APP-ANDROID || APP-IOS
this.ctx.reset()
// #endif
// #ifdef APP-HARMONY
this.ctx.clearRect(0,0,100000,100000)
// #endif
}
_draw() {
// #ifdef APP-ANDROID || APP-IOS
this.ctx.update()
// #endif
}
// addHistory() { }
clear() {
// this.ctx.reset()
// this.ctx.update()
this._clear()
this._draw()
this.isEmpty = true
undoStack = [] as LimeSignatureLine[];
redoStack = [] as LimeSignatureLine[];
points = [] as LimeSignaturePoint[];
}
undo() {
if(redoStack.length == this.options.maxHistoryLength && this.options.maxHistoryLength != 0){
return
}
// this.ctx.reset()
this._clear()
if(undoStack.length > 0){
const lastPath : LimeSignatureLine = undoStack.pop()!;
redoStack.push(lastPath);
if(undoStack.length == 0){
this.isEmpty = true
// this.ctx.update()
this._draw()
return
}
for (let l = 0; l < undoStack.length; l++) {
for (let i = 1; i < undoStack[l].length; i++) {
const last = undoStack[l][i - 1]
const point = undoStack[l][i]
this.drawLine(point, last, point.w!, point.c!)
}
}
} else {
// this.ctx.update()
this._draw()
}
}
redo() {
if(redoStack.length < 1) return
const lastPath : LimeSignatureLine = redoStack.pop()!;
undoStack.push(lastPath);
this.isEmpty = false
for (let l = 0; l < undoStack.length; l++) {
for (let i = 1; i < undoStack[l].length; i++) {
const last = undoStack[l][i - 1]
const point = undoStack[l][i]
this.drawLine(point, last, point.w!, point.c!)
}
}
}
// restore() { }
}
\ No newline at end of file
export interface SignaturePadProps {
/**
* 绘图样式(CSS样式字符串)
*/
styles: string
/**
* 画笔颜色
*/
penColor: string
/**
* 画笔粗细(像素)
*/
penSize: number
/**
* 背景颜色
*/
backgroundColor: string
/**
* 是否开启平滑绘制
*/
openSmooth: boolean
/**
* 最小笔触宽度
*/
minLineWidth: number
/**
* 最大笔触宽度
*/
maxLineWidth: number
/**
* 最小绘制速度(像素/秒)
*/
minSpeed: number
/**
* 最大宽度差异率
*/
maxWidthDiffRate: number
/**
* 历史记录最大长度
*/
maxHistoryLength: number
/**
* 是否禁止滚动穿透
*/
disableScroll: boolean
/**
* 组件是否禁用
*/
disabled: boolean
/**
* 是否横屏模式
*/
landscape: boolean
}
\ No newline at end of file
export function compareVersion(v1, v2) {
v1 = v1.split('.')
v2 = v2.split('.')
const len = Math.max(v1.length, v2.length)
while (v1.length < len) {
v1.push('0')
}
while (v2.length < len) {
v2.push('0')
}
for (let i = 0; i < len; i++) {
const num1 = parseInt(v1[i], 10)
const num2 = parseInt(v2[i], 10)
if (num1 > num2) {
return 1
} else if (num1 < num2) {
return -1
}
}
return 0
}
function gte(version) {
let { SDKVersion } = uni.getSystemInfoSync()
// #ifdef MP-ALIPAY
SDKVersion = my.SDKVersion
// #endif
return compareVersion(SDKVersion, version) >= 0;
}
export function canIUseCanvas2d() {
// #ifdef MP-WEIXIN
return gte('2.9.0');
// #endif
// #ifdef MP-ALIPAY
return gte('2.7.0');
// #endif
// #ifdef MP-TOUTIAO
return gte('1.78.0');
// #endif
return false
}
export const wrapEvent = (e) => {
if (!e) return;
if (!e.preventDefault) {
e.preventDefault = function() {};
}
return e;
}
export const requestAnimationFrame = (cb) => {
setTimeout(cb, 30)
}
// #ifdef MP
export const prefix = () => {
// #ifdef MP-TOUTIAO
return tt
// #endif
// #ifdef MP-WEIXIN
return wx
// #endif
// #ifdef MP-BAIDU
return swan
// #endif
// #ifdef MP-ALIPAY
return my
// #endif
// #ifdef MP-QQ
return qq
// #endif
// #ifdef MP-360
return qh
// #endif
}
// #endif
/**
* base64转路径
* @param {Object} base64
*/
export function base64ToPath(base64) {
const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64) || [];
return new Promise((resolve, reject) => {
// #ifdef MP
const p = prefix()
const fs = p.getFileSystemManager()
//自定义文件名
if (!format) {
reject(new Error('ERROR_BASE64SRC_PARSE'))
}
const time = new Date().getTime();
const filePath = `${p.env.USER_DATA_PATH}/${time}.${format}`;
fs.writeFile({
filePath,
data: base64.split(',')[1],
encoding: 'base64',
success() {
resolve(filePath)
},
fail(err) {
reject(err)
}
})
// #endif
// #ifdef APP-PLUS
const bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
bitmap.loadBase64Data(base64, () => {
if (!format) {
reject(new Error('ERROR_BASE64SRC_PARSE'))
}
const time = new Date().getTime();
const filePath = `_doc/uniapp_temp/${time}.${format}`
bitmap.save(filePath, {},
() => {
bitmap.clear()
resolve(filePath)
},
(error) => {
bitmap.clear()
reject(error)
})
}, (error) => {
bitmap.clear()
reject(error)
})
// #endif
})
}
export function sleep(delay) {
return new Promise(resolve => setTimeout(resolve, delay))
}
export function getRect(selector, options = {}) {
const typeDefault = 'boundingClientRect'
const { context, type = typeDefault} = options
return new Promise((resolve, reject) => {
const dom = uni.createSelectorQuery().in(context).select(selector);
const result = (rect) => {
if(rect) {
resolve(rect)
} else {
reject()
}
}
if(type == typeDefault) {
dom[type](result).exec()
} else {
dom[type]({
node: true,
size: true,
rect: true
}, result).exec()
}
});
};
export function isTransparent(color) {
// 判断颜色是否为 transparent
if (color === 'transparent') {
return true;
}
// 判断颜色是否为 rgba 的 a 为 0
if (color.startsWith('rgba')) {
const regex = /\d+(\.\d+)?/g;
const matches = color.match(regex);
if (matches !== null) {
const alpha = parseFloat(matches[3]);
if (alpha === 0) {
return true;
}
}
}
return false;
}
\ No newline at end of file
<template>
<view style="height: 950rpx;">
<l-signature ref="signature" :pen-color="penColor" :pen-size="10" @change="change"></l-signature>
</view>
<image style="width: 750rpx;" :src="url" v-if="url" mode="widthFix"></image>
<!-- <view style="height: 200rpx; overflow: visible;"></view> -->
<view style="padding:16px">
<button type="primary" style="margin-bottom:10px" @click="clear">清空</button>
<button type="primary" style="margin-bottom:10px" @click="undo">撤消</button>
<button type="primary" style="margin-bottom:10px" @click="redo">恢复</button>
<button type="primary" style="margin-bottom:10px" @click="save">生成</button>
</view>
</template>
<script lang="uts">
import type {LimeSignatureToTempFilePathOptions, LimeSignatureToFileSuccess} from '@/uni_modules/lime-signature'
export default {
data() {
return {
penColor: 'red',
url: ''
}
},
methods: {
change(isEmpty:boolean) {
console.log('isEmpty:::', isEmpty)
},
clear() {
const signature = this.$refs['signature'] as LSignatureComponentPublicInstance
signature.clear()
},
undo() {
const signature = this.$refs['signature'] as LSignatureComponentPublicInstance
signature.undo()
},
redo() {
const signature = this.$refs['signature'] as LSignatureComponentPublicInstance
signature.redo()
},
save() {
const signature = this.$refs['signature'] as LSignatureComponentPublicInstance
signature.canvasToTempFilePath({
success: (res : LimeSignatureToFileSuccess) : void => {
console.log('isEmpty', res.isEmpty)
this.url = res.tempFilePath
}
} as LimeSignatureToTempFilePathOptions)
}
},
mounted() {
setTimeout(() => {
this.penColor = 'blue'
}, 2000)
}
}
</script>
<style>
</style>
\ No newline at end of file
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title></title>
<style type="text/css">
html,
body,
canvas {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
overflow-y: hidden;
background-color: transparent;
}
</style>
</head>
<body>
<canvas id="lime-signature"></canvas>
<script type="text/javascript" src="./uni.webview.1.5.3.js"></script>
<script type="text/javascript" src="./signature.js"></script>
<script>
var signature = null;
var timer = null;
var isStart = false;
var options = null
console.log = function(...args) {
postMessage(args);
};
// function stringify(key, value) {
// if (typeof value === 'object' && value !== null) {
// if (cache.indexOf(value) !== -1) {
// return;
// }
// cache.push(value);
// }
// return value;
// };
function checkAndEmitEmptyStatus() {
setTimeout(() => {
if (signature) {
const isEmpty = signature.isEmpty()
emit({
isEmpty
});
}
}, 0)
}
function emit(event, data) {
postMessage({
event,
data: typeof data !== "object" && data !== null ? data : JSON.stringify(data),
});
// cache = [];
}
function postMessage(data) {
uni.postMessage({
data
});
}
function update(v = {}) {
if (signature) {
options = v
signature.pen.setOption(v);
} else {
signature = new Signature.Signature({
el: "lime-signature"
});
canvasEl = signature.canvas.get("el");
options = v
signature.pen.setOption(v)
const width = signature.canvas.get("width");
const height = signature.canvas.get("height");
canvasEl.addEventListener('touchend', checkAndEmitEmptyStatus)
emit({
changeSize: {
width,
height
}
})
}
}
function clear() {
signature.clear()
checkAndEmitEmptyStatus()
}
function undo() {
signature.undo()
checkAndEmitEmptyStatus()
}
function redo() {
signature.redo()
checkAndEmitEmptyStatus()
}
function isEmpty() {
const isEmpty = signature.isEmpty()
emit({
isEmpty
});
}
function isTransparent(color) {
// 判断颜色是否为 transparent
if (color === 'transparent') {
return true;
}
// 判断颜色是否为 rgba 的 a 为 0
if (color.startsWith('rgba')) {
const regex = /\d+(\.\d+)?/g;
const matches = color.match(regex);
if (matches !== null) {
const alpha = parseFloat(matches[3]);
if (alpha === 0) {
return true;
}
}
}
return false;
}
function mask(param) {
clearTimeout(timer);
let {
destWidth = 0, destHeight = 0
} = param
let width = this.signature.canvas.get('width')
let height = this.signature.canvas.get('height')
let canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d');
const pixelRatio = signature.canvas.get('pixelRatio')
canvas.width = width * pixelRatio
canvas.height = height * pixelRatio
this.signature.pen.getMaskedImageData((imageData) => {
ctx.putImageData(imageData, 0, 0);
if (destWidth && destHeight) {
const _canvas = document.createElement('canvas')
_canvas.width = destWidth
_canvas.height = destHeight
const _context = _canvas.getContext('2d')
_context.drawImage(canvas, 0, 0, destWidth, destHeight)
canvas.remove()
canvas = _canvas
}
const path = canvas.toDataURL();
canvas.remove()
if (typeof path == "string") {
const index = Math.ceil(path.length / 8);
for (var i = 0; i < 8; i++) {
if (i == 7) {
emit({
"success": path.substr(i * index, index)
});
} else {
emit({
"file": path.substr(i * index, index)
});
}
}
} else {
console.error("canvas no data");
emit({
"fail": "canvas no data"
});
}
})
}
function save(param) {
// delete param.success;
// delete param.fail;
clearTimeout(timer);
timer = setTimeout(() => {
let {
fileType = 'png', quality = 1, n, destWidth = 0, destHeight = 0
} = param
const type = `image/${fileType}`.replace(/jpg/, 'jpeg');
const {
backgroundColor,
landscape,
boundingBox
} = options
const flag = backgroundColor || landscape || boundingBox || destWidth && destHeight
let path = canvasEl.toDataURL(!flag && type, !flag && quality)
if (flag) {
let canvas = document.createElement('canvas')
const pixelRatio = signature.canvas.get('pixelRatio')
let width = signature.canvas.get('width')
let height = signature.canvas.get('height')
let x = 0
let y = 0
const next = () => {
const size = [width, height]
if (landscape) {
size.reverse()
}
canvas.width = size[0] * pixelRatio
canvas.height = size[1] * pixelRatio
const param = [x, y, width, height, 0, 0, width, height].map(item => item * pixelRatio)
const context = canvas.getContext('2d')
// context.scale(pixelRatio, pixelRatio)
if (landscape) {
context.translate(0, width * pixelRatio)
context.rotate(-Math.PI / 2)
}
if (backgroundColor && !isTransparent(backgroundColor)) {
context.fillStyle = backgroundColor
context.fillRect(0, 0, width * pixelRatio, height * pixelRatio)
}
const drawImage = () => {
}
// param
context.drawImage(signature.canvas.get('el'), ...param)
if (destWidth && destHeight) {
const _canvas = document.createElement('canvas')
_canvas.width = destWidth
_canvas.height = destHeight
const _context = _canvas.getContext('2d')
_context.drawImage(canvas, 0, 0, destWidth, destHeight)
canvas.remove()
canvas = _canvas
}
path = canvas.toDataURL(type, quality)
canvas.remove()
}
if (boundingBox) {
const res = signature.getContentBoundingBox()
width = res.width
height = res.height
x = res.startX
y = res.startY
next()
} else {
next()
}
}
if (typeof path == "string") {
const index = Math.ceil(path.length / 8);
for (var i = 0; i < 8; i++) {
if (i == 7) {
emit({
"success": path.substr(i * index, index)
});
} else {
emit({
"file": path.substr(i * index, index)
});
}
}
} else {
console.error("canvas no data");
emit({
"fail": "canvas no data"
});
}
}, 30);
}
</script>
</body>
</html>
\ No newline at end of file
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e=e||self).uni=n()}(this,(function(){"use strict";try{var e={};Object.defineProperty(e,"passive",{get:function(){!0}}),window.addEventListener("test-passive",null,e)}catch(e){}var n=Object.prototype.hasOwnProperty;function i(e,i){return n.call(e,i)}var t=[];function o(){return window.__dcloud_weex_postMessage||window.__dcloud_weex_}var r=function(e,n){var i={options:{timestamp:+new Date},name:e,arg:n};if(o()){if("postMessage"===e){var r={data:[n]};return window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(r):window.__dcloud_weex_.postMessage(JSON.stringify(r))}var a={type:"WEB_INVOKE_APPSERVICE",args:{data:i,webviewIds:t}};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessageToService(a):window.__dcloud_weex_.postMessageToService(JSON.stringify(a))}if(!window.plus)return window.parent.postMessage({type:"WEB_INVOKE_APPSERVICE",data:i,pageId:""},"*");if(0===t.length){var d=plus.webview.currentWebview();if(!d)throw new Error("plus.webview.currentWebview() is undefined");var s=d.parent(),w="";w=s?s.id:d.id,t.push(w)}if(plus.webview.getWebviewById("__uniapp__service"))plus.webview.postMessageToUniNView({type:"WEB_INVOKE_APPSERVICE",args:{data:i,webviewIds:t}},"__uniapp__service");else{var u=JSON.stringify(i);plus.webview.getLaunchWebview().evalJS('UniPlusBridge.subscribeHandler("'.concat("WEB_INVOKE_APPSERVICE",'",').concat(u,",").concat(JSON.stringify(t),");"))}},a={navigateTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;r("navigateTo",{url:encodeURI(n)})},navigateBack:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.delta;r("navigateBack",{delta:parseInt(n)||1})},switchTab:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;r("switchTab",{url:encodeURI(n)})},reLaunch:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;r("reLaunch",{url:encodeURI(n)})},redirectTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;r("redirectTo",{url:encodeURI(n)})},getEnv:function(e){o()?e({nvue:!0}):window.plus?e({plus:!0}):e({h5:!0})},postMessage:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};r("postMessage",e.data||{})}},d=/uni-app/i.test(navigator.userAgent),s=/Html5Plus/i.test(navigator.userAgent),w=/complete|loaded|interactive/;var u=window.my&&navigator.userAgent.indexOf("AlipayClient")>-1;var g=window.swan&&window.swan.webView&&/swan/i.test(navigator.userAgent);var c=window.qq&&window.qq.miniProgram&&/QQ/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var v=window.tt&&window.tt.miniProgram&&/toutiaomicroapp/i.test(navigator.userAgent);var m=window.wx&&window.wx.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var p=window.qa&&/quickapp/i.test(navigator.userAgent);var f=window.ks&&window.ks.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var l=window.tt&&window.tt.miniProgram&&/Lark|Feishu/i.test(navigator.userAgent);var _=window.jd&&window.jd.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);for(var E,b=function(){window.UniAppJSBridge=!0,document.dispatchEvent(new CustomEvent("UniAppJSBridgeReady",{bubbles:!0,cancelable:!0}))},h=[function(e){if(d||s)return window.__dcloud_weex_postMessage||window.__dcloud_weex_?document.addEventListener("DOMContentLoaded",e):window.plus&&w.test(document.readyState)?setTimeout(e,0):document.addEventListener("plusready",e),a},function(e){if(m)return window.WeixinJSBridge&&window.WeixinJSBridge.invoke?setTimeout(e,0):document.addEventListener("WeixinJSBridgeReady",e),window.wx.miniProgram},function(e){if(c)return window.QQJSBridge&&window.QQJSBridge.invoke?setTimeout(e,0):document.addEventListener("QQJSBridgeReady",e),window.qq.miniProgram},function(e){if(u){document.addEventListener("DOMContentLoaded",e);var n=window.my;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){if(g)return document.addEventListener("DOMContentLoaded",e),window.swan.webView},function(e){if(v)return document.addEventListener("DOMContentLoaded",e),window.tt.miniProgram},function(e){if(p){window.QaJSBridge&&window.QaJSBridge.invoke?setTimeout(e,0):document.addEventListener("QaJSBridgeReady",e);var n=window.qa;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){if(f)return window.WeixinJSBridge&&window.WeixinJSBridge.invoke?setTimeout(e,0):document.addEventListener("WeixinJSBridgeReady",e),window.ks.miniProgram},function(e){if(l)return document.addEventListener("DOMContentLoaded",e),window.tt.miniProgram},function(e){if(_)return window.JDJSBridgeReady&&window.JDJSBridgeReady.invoke?setTimeout(e,0):document.addEventListener("JDJSBridgeReady",e),window.jd.miniProgram},function(e){return document.addEventListener("DOMContentLoaded",e),a}],y=0;y<h.length&&!(E=h[y](b));y++);E||(E={});var B="undefined"!=typeof uni?uni:{};if(!B.navigateTo)for(var S in E)i(E,S)&&(B[S]=E[S]);return B.webView=E,B}));
// @ts-nocheck
export type LimeSignatureToFileSuccess = {
tempFilePath: string
isEmpty: boolean
}
export type LimeSignatureToFileSuccessCallback = (res : LimeSignatureToFileSuccess) => void
export type LimeSignatureToFileFailCallback = (res : TakeSnapshotFail) => void
export type LimeSignatureToFileCompleteCallback = (res : any) => void
export type LimeSignatureToTempFilePathOptions = {
success?: LimeSignatureToFileSuccessCallback
fail?: LimeSignatureToFileFailCallback
complete?: LimeSignatureToFileCompleteCallback
format?: string
}
export type LimeSignatureOptions = {
penColor : string
// backgroundColor : string
openSmooth : boolean
disableScroll : boolean
disabled : boolean
penSize : number
minLineWidth : number
maxLineWidth : number
minSpeed : number
maxWidthDiffRate : number
maxHistoryLength : number
}
export type LimeSignaturePoint = {
x: number
y: number
c?: string
w?: number
}
export type LimeSignatureLine = LimeSignaturePoint[]
\ No newline at end of file
{
"id": "lime-signature",
"displayName": "lime-signature 手写板-签名签字",
"version": "1.5.7",
"description": "手写板签名插件:一款实用的签名插件,支持横屏、背景色、笔画颜色、笔画大小等功能,可生成有内容的区域,减小图片尺寸,节省空间。支持uniapp/uniappx",
"keywords": [
"写字",
"签名",
"电子签名",
"横屏",
"uvue"
],
"repository": "",
"engines": {
"HBuilderX": "^3.5.4",
"uni-app": "^4.74",
"uni-app-x": "^4.75"
},
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "",
"type": "component-vue",
"darkmode": "x",
"i18n": "x",
"widescreen": "x"
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "√",
"aliyun": "√",
"alipay": "x"
},
"client": {
"uni-app": {
"vue": {
"vue2": "√",
"vue3": "√"
},
"web": {
"safari": "√",
"chrome": "√"
},
"app": {
"vue": "√",
"nvue": "-",
"android": {
"extVersion": "",
"minVersion": "21"
},
"ios": "√",
"harmony": "√"
},
"mp": {
"weixin": "√",
"alipay": "√",
"toutiao": "√",
"baidu": "√",
"kuaishou": "√",
"jd": "√",
"harmony": "-",
"qq": "√",
"lark": "√"
},
"quickapp": {
"huawei": "-",
"union": "-"
}
},
"uni-app-x": {
"web": {
"safari": "√",
"chrome": "√"
},
"app": {
"android": {
"extVersion": "",
"minVersion": "21"
},
"ios": "√",
"harmony": "√"
},
"mp": {
"weixin": "√"
}
}
}
}
}
}
\ No newline at end of file
# LimeSignature 写字板
一款用于业务签名等场景的写字板插件,支持横屏、压感模拟、撤销/重做等功能。
## 文档链接
📚 详细文档请访问以下站点:
- [signature 文档 - 站点1](https://limex.qcoon.cn/components/signature.html)
- [signature 文档 - 站点2](https://limeui.netlify.app/components/signature.html)
- [signature 文档 - 站点3](https://limeui.familyzone.top/components/signature.html)
## 安装方法
1. 在 uni-app 插件市场中搜索并导入 `lime-signature`
2. 导入后可能需要重新编译项目。
## 代码演示
### 基本用法
```html
<view style="width: 750rpx ;height: 750rpx;">
<l-signature disableScroll ref="signatureRef" :penColor="penColor" :penSize="penSize" :openSmooth="openSmooth" ></l-signature>
</view>
<view>
<button @click="onClick('clear')">清空</button>
<button @click="onClick('undo')">撤消</button>
<button @click="onClick('save')">保存</button>
<!-- uvue 不支持 openSmooth -->
<button @click="onClick('openSmooth')">压感{{openSmooth?'开':'关'}}</button>
</view>
```
### Uniapp
```js
export default {
data() {
return {
title: 'Hello',
penColor: 'red',
penSize: 5,
url: '',
openSmooth: true
}
},
methods: {
onClick(type) {
if(type == 'openSmooth') {
this.openSmooth = !this.openSmooth
return
}
if (type == 'save') {
this.$refs.signatureRef.canvasToTempFilePath({
success: (res) => {
// 是否为空画板 无签名
console.log(res.isEmpty)
// 生成图片的临时路径
// H5 生成的是base64
this.url = res.tempFilePath
}
})
return
}
if (this.$refs.signatureRef)
this.$refs.signatureRef[type]()
}
}
}
```
### Uniappx
```js
import {LimeSignatureToTempFilePathOptions, LimeSignatureToFileSuccess} from '@/uni_modules/lime-signature'
export default {
data() {
return {
title: 'Hello',
penColor: 'red',
penSize: 5,
url: '',
openSmooth: true
}
},
methods: {
onClick(type: string) {
const signatureRef = this.$refs['signatureRef'] as LSignatureComponentPublicInstance
// APP 不支持
// #ifndef APP
if(type == 'openSmooth') {
this.openSmooth = !this.openSmooth
}
// #endif
if (type == 'save') {
signatureRef.canvasToTempFilePath({
success: (res: LimeSignatureToFileSuccess) => {
// 是否为空画板 无签名
console.log(res.isEmpty)
// 生成图片的临时路径
// H5 生成的是base64
this.url = res.tempFilePath
}
} as LimeSignatureToTempFilePathOptions)
return
}
if(type == 'undo'){
signatureRef.undo()
}
if(type == 'redo'){
signatureRef.redo()
}
if(type == 'clear'){
signatureRef.clear()
}
}
}
}
```
### 横屏
通过设置`landscape`,改变生成图片的方向,达到横屏的作用
```html
<view style="width: 100vw; height: 100vh;">
<l-signature landscape></l-signature>
</view>
<view style="transform: rotate(90deg);">
<button @click="onClick('clear')">清空</button>
<button @click="onClick('undo')">撤消</button>
<button @click="onClick('save')">保存</button>
<button @click="onClick('openSmooth')">压感{{openSmooth?'开':'关'}}</button>
</view>
```
## API 文档
### Props
| 参数 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| `penSize` | 画笔大小 | `number` | `2` |
| `minLineWidth` | 线条最小宽度 | `number` | `2` |
| `maxLineWidth` | 线条最大宽度 | `number` | `6` |
| `penColor` | 画笔颜色 | `string` | `black` |
| `backgroundColor` | 背景颜色(透明背景需留空) | `string` | `` |
| `openSmooth` | 是否模拟压感 | `boolean` | `false` |
| `landscape` | 横屏模式 | `boolean` | `false` |
| `disableScroll` | 禁用滚动 | `boolean` | `true` |
| `disabled` | 禁用写字板 | `boolean` | `false` |
### 事件
| 事件名 | 说明 |
| --- | --- |
| `undo` | 撤销操作 |
| `clear` | 清空画板 |
| `canvasToTempFilePath` | 保存为图片 |
## 支持与赞赏
如果你觉得本插件解决了你的问题,可以考虑支持作者:
| 支付宝赞助 | 微信赞助 |
|------------|------------|
| ![](https://testingcf.jsdelivr.net/gh/liangei/image@1.9/alipay.png) | ![](https://testingcf.jsdelivr.net/gh/liangei/image@1.9/wpay.png) |
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!