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 5045 additions and 90 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
......@@ -48,7 +48,9 @@
.icon-change-account { width: calc(100vmin * (1173 / 768) * 0.013640238704177323); height: calc(100vmin * (1173 / 768) * 0.013640238704177323);
background-position: calc(100vmin * (1173 / 768) * -0.34654731457800514) calc(100vmin * (1173 / 768) * -0.3052003410059676);}
.icon-clone { width: calc(100vmin * (1173 / 768) * 0.010230179028132993); height: calc(100vmin * (1173 / 768) * 0.010230179028132993);
background-position: calc(100vmin * (1173 / 768) * -0.36615515771526) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
background-position: calc(100vmin * (1173 / 768) * -0.4062233589087809) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-collapse-all { width: calc(100vmin * (1173 / 768) * 0.010230179028132993); height: calc(100vmin * (1173 / 768) * 0.010230179028132993);
background-position: calc(100vmin * (1173 / 768) * -0.42284739982949704) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-collapse-all { width: calc(100vmin * (1173 / 768) * 0.010230179028132993); height: calc(100vmin * (1173 / 768) * 0.010230179028132993);
background-position: calc(100vmin * (1173 / 768) * -0.38277919863597615) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-coupon-arrow { width: calc(100vmin * (1173 / 768) * 0.013640238704177323); height: calc(100vmin * (1173 / 768) * 0.013640238704177323);
......@@ -105,10 +107,12 @@
background-position: calc(100vmin * (1173 / 768) * -0.45524296675191817) calc(100vmin * (1173 / 768) * -0.4113384484228474);}
.icon-end-right { width: calc(100vmin * (1173 / 768) * 0.027280477408354646); height: calc(100vmin * (1173 / 768) * 0.04092071611253197);
background-position: calc(100vmin * (1173 / 768) * -0.6547314578005116) calc(100vmin * (1173 / 768) * -0.5234441602728048);}
.icon-end-right { width: calc(100vmin * (1173 / 768) * 0.027280477408354646); height: calc(100vmin * (1173 / 768) * 0.04092071611253197);
background-position: calc(100vmin * (1173 / 768) * -0.6547314578005116) calc(100vmin * (1173 / 768) * -0.5234441602728048);}
.icon-equity-order { width: calc(100vmin * (1173 / 768) * 0.04092071611253197); height: calc(100vmin * (1173 / 768) * 0.04092071611253197);
background-position: calc(100vmin * (1173 / 768) * 0) calc(100vmin * (1173 / 768) * -0.5907928388746803);}
.icon-equityClose { width: calc(100vmin * (1173 / 768) * 0.010230179028132993); height: calc(100vmin * (1173 / 768) * 0.010230179028132993);
background-position: calc(100vmin * (1173 / 768) * -0.39940323955669227) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
background-position: calc(100vmin * (1173 / 768) * -0.4394714407502131) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-equityTip { width: calc(100vmin * (1173 / 768) * 0.013640238704177323); height: calc(100vmin * (1173 / 768) * 0.013640238704177323);
background-position: calc(100vmin * (1173 / 768) * -0.4752770673486786) calc(100vmin * (1173 / 768) * -0.4113384484228474);}
.icon-evaluation-management { width: calc(100vmin * (1173 / 768) * 0.04092071611253197); height: calc(100vmin * (1173 / 768) * 0.04092071611253197);
......@@ -134,7 +138,7 @@
.icon-feedback { width: calc(100vmin * (1173 / 768) * 0.027280477408354646); height: calc(100vmin * (1173 / 768) * 0.027280477408354646);
background-position: calc(100vmin * (1173 / 768) * -0.3537936913895993) calc(100vmin * (1173 / 768) * -0.6381074168797954);}
.icon-feedbackIcon { width: calc(100vmin * (1173 / 768) * 0.011082693947144074); height: calc(100vmin * (1173 / 768) * 0.011082693947144074);
background-position: calc(100vmin * (1173 / 768) * -0.33034953111679455) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
background-position: calc(100vmin * (1173 / 768) * -0.37041773231031544) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-ffdyj-icon { width: calc(100vmin * (1173 / 768) * 0.017050298380221655); height: calc(100vmin * (1173 / 768) * 0.017050298380221655);
background-position: calc(100vmin * (1173 / 768) * -0.7020460358056266) calc(100vmin * (1173 / 768) * -0.6300085251491901);}
.icon-filter { width: calc(100vmin * (1173 / 768) * 0.013640238704177323); height: calc(100vmin * (1173 / 768) * 0.013640238704177323);
......@@ -212,7 +216,7 @@
.icon-logo { width: calc(100vmin * (1173 / 768) * 0.06820119352088662); height: calc(100vmin * (1173 / 768) * 0.06820119352088662);
background-position: calc(100vmin * (1173 / 768) * -0.5647911338448423) calc(100vmin * (1173 / 768) * -0.10017050298380221);}
.icon-lssl-icon { width: calc(100vmin * (1173 / 768) * 0.011935208866155157); height: calc(100vmin * (1173 / 768) * 0.011935208866155157);
background-position: calc(100vmin * (1173 / 768) * -0.22037510656436488) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
background-position: calc(100vmin * (1173 / 768) * -0.26044330775788577) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-mask-del { width: calc(100vmin * (1173 / 768) * 0.03410059676044331); height: calc(100vmin * (1173 / 768) * 0.03410059676044331);
background-position: calc(100vmin * (1173 / 768) * -0.6547314578005116) calc(100vmin * (1173 / 768) * -0.3614663256606991);}
.icon-mask-edit { width: calc(100vmin * (1173 / 768) * 0.03410059676044331); height: calc(100vmin * (1173 / 768) * 0.03410059676044331);
......@@ -230,7 +234,7 @@
.icon-no-picture { width: calc(100vmin * (1173 / 768) * 0.021312872975277068); height: calc(100vmin * (1173 / 768) * 0.021312872975277068);
background-position: calc(100vmin * (1173 / 768) * -0.7020460358056266) calc(100vmin * (1173 / 768) * -0.14791133844842286);}
.icon-normal { width: calc(100vmin * (1173 / 768) * 0.011935208866155157); height: calc(100vmin * (1173 / 768) * 0.011935208866155157);
background-position: calc(100vmin * (1173 / 768) * -0.23870417732310314) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
background-position: calc(100vmin * (1173 / 768) * -0.27877237851662406) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-notice-script { width: calc(100vmin * (1173 / 768) * 0.04092071611253197); height: calc(100vmin * (1173 / 768) * 0.04092071611253197);
background-position: calc(100vmin * (1173 / 768) * -0.3312020460358056) calc(100vmin * (1173 / 768) * -0.5907928388746803);}
.icon-notice-study { width: calc(100vmin * (1173 / 768) * 0.04092071611253197); height: calc(100vmin * (1173 / 768) * 0.04092071611253197);
......@@ -324,7 +328,7 @@
.icon-role-2 { width: calc(100vmin * (1173 / 768) * 0.028985507246376812); height: calc(100vmin * (1173 / 768) * 0.028985507246376812);
background-position: calc(100vmin * (1173 / 768) * -0.1837169650468883) calc(100vmin * (1173 / 768) * -0.6381074168797954);}
.icon-rule { width: calc(100vmin * (1173 / 768) * 0.011935208866155157); height: calc(100vmin * (1173 / 768) * 0.011935208866155157);
background-position: calc(100vmin * (1173 / 768) * -0.2570332480818414) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
background-position: calc(100vmin * (1173 / 768) * -0.2971014492753623) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-scan { width: calc(100vmin * (1173 / 768) * 0.013640238704177323); height: calc(100vmin * (1173 / 768) * 0.013640238704177323);
background-position: calc(100vmin * (1173 / 768) * -0.6355498721227621) calc(100vmin * (1173 / 768) * -0.6751918158567775);}
.icon-scanIcon { width: calc(100vmin * (1173 / 768) * 0.013640238704177323); height: calc(100vmin * (1173 / 768) * 0.013640238704177323);
......@@ -374,7 +378,7 @@
.icon-study-active { width: calc(100vmin * (1173 / 768) * 0.0443307757885763); height: calc(100vmin * (1173 / 768) * 0.0443307757885763);
background-position: calc(100vmin * (1173 / 768) * -0.2028985507246377) calc(100vmin * (1173 / 768) * -0.5400682011935208);}
.icon-study-tips { width: calc(100vmin * (1173 / 768) * 0.011935208866155157); height: calc(100vmin * (1173 / 768) * 0.011935208866155157);
background-position: calc(100vmin * (1173 / 768) * -0.2753623188405797) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
background-position: calc(100vmin * (1173 / 768) * -0.3154305200341006) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-study { width: calc(100vmin * (1173 / 768) * 0.0443307757885763); height: calc(100vmin * (1173 / 768) * 0.0443307757885763);
background-position: calc(100vmin * (1173 / 768) * -0.2536231884057971) calc(100vmin * (1173 / 768) * -0.5400682011935208);}
.icon-submit { width: calc(100vmin * (1173 / 768) * 0.017050298380221655); height: calc(100vmin * (1173 / 768) * 0.017050298380221655);
......@@ -390,7 +394,7 @@
.icon-tag-checked { width: calc(100vmin * (1173 / 768) * 0.02557544757033248); height: calc(100vmin * (1173 / 768) * 0.013640238704177323);
background-position: calc(100vmin * (1173 / 768) * -0.7020460358056266) calc(100vmin * (1173 / 768) * -0.44075021312872975);}
.icon-task-pass { width: calc(100vmin * (1173 / 768) * 0.011935208866155157); height: calc(100vmin * (1173 / 768) * 0.011935208866155157);
background-position: calc(100vmin * (1173 / 768) * -0.293691389599318) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
background-position: calc(100vmin * (1173 / 768) * -0.3337595907928389) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-tdcj-icon { width: calc(100vmin * (1173 / 768) * 0.017050298380221655); height: calc(100vmin * (1173 / 768) * 0.017050298380221655);
background-position: calc(100vmin * (1173 / 768) * -0.25788576300085253) calc(100vmin * (1173 / 768) * -0.6751918158567775);}
.icon-time-icon { width: calc(100vmin * (1173 / 768) * 0.013640238704177323); height: calc(100vmin * (1173 / 768) * 0.013640238704177323);
......@@ -414,9 +418,9 @@
.icon-total { width: calc(100vmin * (1173 / 768) * 0.013640238704177323); height: calc(100vmin * (1173 / 768) * 0.013640238704177323);
background-position: calc(100vmin * (1173 / 768) * -0.1402387041773231) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-two-arrow { width: calc(100vmin * (1173 / 768) * 0.011935208866155157); height: calc(100vmin * (1173 / 768) * 0.010230179028132993);
background-position: calc(100vmin * (1173 / 768) * -0.34782608695652173) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
background-position: calc(100vmin * (1173 / 768) * -0.3878942881500426) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-up-arrow { width: calc(100vmin * (1173 / 768) * 0.011935208866155157); height: calc(100vmin * (1173 / 768) * 0.011935208866155157);
background-position: calc(100vmin * (1173 / 768) * -0.31202046035805625) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
background-position: calc(100vmin * (1173 / 768) * -0.35208866155157714) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-upload-play { width: calc(100vmin * (1173 / 768) * 0.017050298380221655); height: calc(100vmin * (1173 / 768) * 0.017050298380221655);
background-position: calc(100vmin * (1173 / 768) * -0.30477408354646207) calc(100vmin * (1173 / 768) * -0.6751918158567775);}
.icon-uploadAdd { width: calc(100vmin * (1173 / 768) * 0.020460358056265986); height: calc(100vmin * (1173 / 768) * 0.020460358056265986);
......@@ -432,4 +436,8 @@
.icon-yw-icon { width: calc(100vmin * (1173 / 768) * 0.015345268542199489); height: calc(100vmin * (1173 / 768) * 0.015345268542199489);
background-position: calc(100vmin * (1173 / 768) * -0.5004262574595055) calc(100vmin * (1173 / 768) * -0.45865302642796246);}
.icon-zj-icon { width: calc(100vmin * (1173 / 768) * 0.013640238704177323); height: calc(100vmin * (1173 / 768) * 0.013640238704177323);
background-position: calc(100vmin * (1173 / 768) * -0.20034100596760443) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
\ No newline at end of file
background-position: calc(100vmin * (1173 / 768) * -0.20034100596760443) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-fullScreen { width: calc(100vmin * (1173 / 768) * 0.013640238704177323); height: calc(100vmin * (1173 / 768) * 0.013640238704177323);
background-position: calc(100vmin * (1173 / 768) * -0.22037510656436488) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
.icon-sign_del { width: calc(100vmin * (1173 / 768) * 0.013640238704177323); height: calc(100vmin * (1173 / 768) * 0.013640238704177323);
background-position: calc(100vmin * (1173 / 768) * -0.24040920716112532) calc(100vmin * (1173 / 768) * -0.6986359761295823);}
\ No newline at end of file
......@@ -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
}
......
<!--工单信息卡片-->
<template>
<view class="order-card">
<view class="order-card-top-box-line flex justify-between">
<view class="flex item-center">
<text class="mr-20">{{ orderCardDetail.customerName }} | {{ orderCardDetail.customerPhone }}</text>
</view>
</view>
<view class="order-card-top-box flex justify-between">
<view class="flex item-center order-value-single flex-shrink0 flex-1">
<text class="mr-20 order-value-single">{{ orderCardDetail.goodName }}</text>
</view>
<view class="status text-center min-width0" :style="{ color: status[orderCardDetail.orderStatus].color, 'background-color': status[orderCardDetail.orderStatus].background }">
{{ status[orderCardDetail.orderStatus].text }}
</view>
</view>
<view class="order-card-bottom-box">
<view class="item-content">
<!-- <image class="status-icon" src="/packageEquity/images/equity-{{ item.orderStatus }}.png" /> -->
<view class="order-list align-center" v-for="(item, sindex) in orderObj" :key="sindex">
<view class="flex" :class="['order', orderObj.length == sindex + 1 ? '' : 'm-b-16']">
<view class="order-label order-value-single">{{ item.label }}</view>
<view class="order-value">
<view v-if="item.key == 'ywly'">车损升级</view>
<view v-else class="order-value-single">{{ orderCardDetail[item.key] || '' }}{{ item.suffix || '' }}</view>
</view>
</view>
</view>
</view>
</view>
<view class="item-footer">
<!-- <view>{{item.createdDate}}</view> -->
<!-- 超管isSuper/商户类型 userType 1账号不可操作 -->
<view v-if="((!userInfo.isSuper && userInfo.userType == 2 && orderCardDetail.orderStatus != 4) || orderCardDetail.orderStatus == 2) && isOrder">
<view class="btn_box_class">
<view class="order-btn default-btn" @click="handleSignature">{{ orderCardDetail.customerNameUrl ? '修改客户签名' : '补录客户签名' }}</view>
<view v-if="orderCardDetail.orderStatus == '2'" class="order-btn default-btn" @click="handlePreviewContract">下载合同</view>
<view v-if="orderCardDetail.orderStatus == '2'" class="order-btn" @click="handlePreviewContract">{{ btnTxt[orderCardDetail.orderStatus] }}</view>
<view v-else class="order-btn" @click="handleRecordOrder">{{ btnTxt[orderCardDetail.orderStatus] }}</view>
</view>
</view>
</view>
<NoticePopup ref="notice" title="提示" text="是否撤销该笔客户工单,撤销后客户工单为「已撤销」状态,不再统计订单数和订单金额。" type="warning"></NoticePopup>
<PublishPopup ref="defeatOrderPopup" popupClass="defeatOrderPopup" type="center" :showClose="true" :isMaskClick="false" title="战败原因">
<template #content>
<view class="defeat-order-box modatcontent">
<textarea class="defeat-textarea" placeholder="请填写战败原因" maxlength="30" v-model="textareaValue" />
</view>
</template>
<template #footer>
<view class="footer-box flex justify-center">
<view class="cancle-btn btn" @click.stop="cancelSelection">取消</view>
<view class="sure-btn btn" @click.stop="confirmSelection">确认</view>
</view>
</template>
</PublishPopup>
</view>
</template>
<script>
import order_mixins from '../../order_mixins.js'
import { interceptionMixin } from '@/mixin/index'
import PublishPopup from '@/components/PublishPopup.vue'
import NoticePopup from '@/components/NoticePopup.vue'
export default {
mixins: [interceptionMixin],
name: 'EquityCard',
props: {
orderCardDetail: {
type: Object,
default: () => ({})
}
},
components: {
PublishPopup,
NoticePopup
},
computed: {
payType() {
return order_mixins.data.payType || {}
},
status() {
return order_mixins.data.equityStatus || {}
}
},
data() {
return {
IMG_URL: 'https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/',
isSettingExpiredTraffic: false, // 是否启用流量失效
selectType: 1,
orderObj: [
{
label: '车架号',
key: 'vin'
},
{
label: '业务来源',
key: 'ywly'
},
{
label: '商品名称',
key: 'goodName'
},
{
label: '服务期限',
key: 'serviceExpire',
suffix: '年'
},
{
label: '商品内容',
key: 'goodServiceName'
}
],
localUserInfo: null,
isOrder: null,
btnTxt: {
0: '去录单',
2: '查看合同',
3: '重新录单'
},
textareaValue: ''
}
},
mounted() {
this.localUserInfo = uni.$storage.get('userInfo')
this.isOrder = !(this.localUserInfo?.isSuper || this.localUserInfo?.loginRole == 3 || this.localUserInfo.loginRole == 5 || this.localUserInfo?.loginRole == 6)
},
_methods: {
copyText(e) {
console.log(e)
uni.setClipboardData({
data: e,
success: () => {
uni.showToast({
title: '复制成功',
icon: 'success',
duration: 2000
})
}
})
},
handleClickBtn(type) {
switch (type) {
case 'upload':
// 处理上传协议
this.uploadContract()
break
case 'handle':
// 处理去处理
this.createorder()
break
case 'price':
// 处理去报价
this.$emit('jump', 'CreateOrder', { paramsData: this.orderCardDetail, type: 'CreateOrder' })
break
case 'pay':
this.$emit('openPay', this.orderCardDetail)
// 处理去支付
break
case 'defeat':
// 处理战败
this.defeatOrder()
break
case 'revoke':
// 处理撤销
this.revokeOrder()
break
case 'default':
// 处理默认情况
break
default:
// 其他情况
break
}
},
//去处理
createorder() {
this.$emit('jump', 'CreateOrder', { paramsData: this.orderCardDetail, type: 'CreateOrder' })
},
// 补录客户签名
handleSignature() {
this.$emit('jump', 'SignName', { paramsData: this.orderCardDetail, type: 'SignName' })
},
showRefundAlert(type) {
const text = type == 'error' ? '订单已发起退款,禁止标记为错误工单!如需标记错误请联系总部运营。' : '订单已发起退款,禁止撤销!如需撤销请联系总部运营。'
uni.showModal({
title: '提示',
content: text,
showCancel: false,
confirmText: '好的'
})
},
confirmSelection() {
if (this.textareaValue) {
uni.$api.equityApi
.updateOrderStatus({
id: this.orderCardDetail.id,
orderStatus: -1,
remark: this.textareaValue
})
.then(res => {
uni.showToast({
title: '提交成功',
icon: 'none'
})
setTimeout(() => {
this.$emit('refresh')
// _this.getList();
}, 500)
})
} else {
uni.showToast({
title: '内容不能为空',
icon: 'none'
})
}
}
},
get methods() {
return this._methods
},
set methods(value) {
this._methods = value
}
}
</script>
<style lang="scss" scoped>
// Popup样式
::v-deep .defeatOrderPopup .uni-popup__wrapper {
position: relative;
border-radius: toRpx(32);
opacity: 1;
width: toRpx(848);
height: toRpx(968);
background-color: #fff !important;
.popup-top-box {
text-align: left;
padding: toRpx(48) toRpx(64);
border-radius: toRpx(32) toRpx(32) 0 0;
background: linear-gradient(180deg, #e6f0ff 0%, #ffffff 100%);
&-title {
color: #1a1a1a;
font-size: toRpx(40);
font-weight: 500;
}
.icon-close {
font-size: toRpx(40) !important;
color: rgba(26, 26, 26, 0.6) !important;
}
}
.modatcontent {
box-sizing: border-box;
padding: 0 toRpx(64);
.modalbox {
display: flex;
align-items: center;
box-sizing: border-box;
border-radius: toRpx(16);
background: #f7f8fa;
height: toRpx(136);
border-radius: toRpx(8);
margin: 0 auto;
color: #292d33;
font-size: toRpx(28);
font-weight: 500;
& + .modalbox {
margin-top: toRpx(16);
}
.sprite-icon {
margin: 0 toRpx(24) 0 toRpx(32);
}
}
.act {
border: toRpx(2) solid #347bff;
background: #347bff1a;
}
}
.footer-box {
width: 100%;
height: toRpx(164);
background-color: #fff;
position: absolute;
bottom: 0;
border-radius: 0 0 toRpx(32) toRpx(32);
.btn {
width: 40%;
height: toRpx(80);
border-radius: toRpx(48);
opacity: 1;
line-height: toRpx(80);
text-align: center;
color: rgba(26, 26, 26, 0.6);
font-size: toRpx(32);
font-weight: 500;
}
.cancle-btn {
background: #f0f1f5;
}
.sure-btn {
color: #fff;
background: linear-gradient(0deg, #2c66f7 0%, #48a6ff 100%);
margin-left: toRpx(32);
}
}
.defeat-textarea {
height: toRpx(568);
border-radius: toRpx(16);
background: #f5f7fa;
width: 100%;
padding: toRpx(24);
box-sizing: border-box;
.uni-input-wrapper {
background: #f5f7fa;
}
}
}
.order-card {
padding: 0 toRpx(32);
border-radius: toRpx(24);
opacity: 1;
background: #ffffff;
box-shadow: 0 toRpx(8) toRpx(24) 0 #2a61eb1a;
margin-bottom: toRpx(24);
}
.status {
padding: toRpx(8);
font-size: toRpx(24);
font-weight: 500;
border-radius: toRpx(4);
border: toRpx(1) solid transparent;
}
.order {
.order-label {
width: toRpx(120);
margin-right: toRpx(24);
font-size: toRpx(24);
color: #999ea8;
font-weight: 400;
flex-shrink: 0;
}
.order-value {
font-size: toRpx(24);
color: #666666;
font-weight: 400;
min-width: 0;
}
.value-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.split {
margin: 0 toRpx(6);
flex-shrink: 0;
}
}
.unit {
margin-right: toRpx(4);
color: #347bff;
font-size: toRpx(26);
font-weight: 700;
}
.price {
color: #347bff;
font-size: toRpx(32);
font-weight: 700;
}
.construction-staff {
width: 50%;
padding: toRpx(10) toRpx(20) toRpx(10) 0;
box-sizing: border-box;
.staff-label {
width: toRpx(120);
margin-right: toRpx(24);
font-size: toRpx(24);
font-weight: 400;
color: #999ea8;
}
.staff-value {
font-size: toRpx(24);
color: #666666;
font-weight: 400;
}
}
.goods-list {
width: 100%;
border-radius: toRpx(16);
opacity: 1;
border-bottom: toRpx(2) solid #f7f7f6;
background: #f5f7fa;
margin: toRpx(20) 0;
padding: toRpx(20) toRpx(32);
.goods {
color: #333333;
font-size: toRpx(28);
font-weight: 400;
margin-bottom: toRpx(16);
&.no-margin {
margin-bottom: 0;
}
.goods-name {
.point {
width: toRpx(12);
height: toRpx(12);
opacity: 1;
border: toRpx(2) solid #4673ff;
border-radius: 50%;
background: #4673ff;
margin-right: toRpx(16);
}
}
}
.goods-more {
color: #4673ff;
font-size: toRpx(24);
font-weight: 400;
text-align: right;
margin-top: toRpx(12);
}
}
.item-footer {
display: flex;
justify-content: flex-end;
align-items: center;
font-size: toRpx(24);
color: #9b9b9e;
border-top: toRpx(1) solid #ededed;
padding: toRpx(20) 0;
}
.btn_box_class {
display: flex;
align-items: center;
}
.order-btn {
box-sizing: border-box;
height: toRpx(56);
/* line-height: var(--fontSize56); */
display: flex;
align-items: center;
justify-content: center;
font-size: toRpx(28);
color: #ffffff;
background: #347bff;
border-radius: toRpx(32);
padding: 0 toRpx(24);
margin-right: toRpx(16);
}
.order-btn:last-child {
margin-right: 0;
}
.order-btn.default-btn {
background: #ffffff;
border: toRpx(2) solid #347bff;
border-radius: toRpx(32);
color: #347bff;
}
.padding_20 {
padding: 0 toRpx(14);
}
.order-list {
margin-bottom: toRpx(12);
}
.order-content {
margin-top: var(--fontSize24);
display: flex;
}
.order-list .good-name {
box-sizing: border-box;
font-weight: 500;
font-size: var(--fontSize30);
color: #333333;
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
-webkit-line-clamp: 2;
}
.order-list .pro-bg {
width: var(--fontSize160);
/* height: auto; */
height: var(--fontSize210);
flex-shrink: 0;
margin-right: var(--fontSize24);
}
.tips {
display: flex;
align-items: center;
font-size: toRpx(24);
width: 100%;
height: toRpx(56);
border-radius: toRpx(8);
opacity: 1;
background: #fef5ea;
margin: toRpx(16) 0;
color: #ff9d0a;
&-text {
margin-top: toRpx(4);
}
.icon-study-tips {
margin-right: toRpx(8);
}
}
.copy-btn {
display: flex;
align-items: center;
margin-left: auto;
color: #808291;
.copy {
margin-right: toRpx(8);
margin-left: toRpx(16);
}
}
.order-card-top-box {
margin-bottom: toRpx(20);
color: #292d33;
font-size: toRpx(30);
font-weight: 500;
}
.order-card-top-box-line {
margin-bottom: toRpx(24);
color: #666666;
font-size: toRpx(24);
border-bottom: toRpx(2) solid #f7f7f6;
padding: toRpx(16) 0;
}
.order-card-bottom-box {
border-bottom: toRpx(2) solid #f7f7f6;
padding-bottom: toRpx(20);
}
.updateInfo {
color: #347bff;
font-size: toRpx(24);
margin-left: toRpx(16);
font-weight: normal;
margin-right: auto;
}
.updateInfo.isHide {
display: none;
}
.flex-shrink0 {
flex-shrink: 0;
}
.min-width0 {
min-width: 0;
}
.order-value-single,
.order-value-item {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
min-width: 0;
}
</style>
<template>
<view class="order-management">
<view class="search-box">
<input class="search-input" placeholder-class="placeholder" v-model="customerName" confirm-type="search" @confirm="search" placeholder="输入客户姓名/商品名称/订单编号/手机号搜索" />
<view class="clear flex" @click="clear">
<uni-icons type="closeempty" size="16" v-if="customerName"></uni-icons>
</view>
</view>
<view class="tab-container flex">
<view class="flex tab-flex-box">
<view class="tab-item" :class="{ active: tabIndex === index }" v-for="(item, index) in tabList" :key="index" @click="switchTab(index)">
<text>{{ item.tabName }}</text>
<text class="num">{{ item.num }}</text>
</view>
</view>
<!-- <view class="flex filter-item justify-center align-center" @click="openFilter">
筛选
<view class="sprite-icon icon-filter"></view>
</view> -->
</view>
<view class="px-48">
<view class="flex tips align-center justify-between" v-if="showTips">
<view class="flex align-center">
<view class="sprite-icon icon-equityTip"></view>
为保障客户权益,请尽快处理!
</view>
<view class="sprite-icon icon-equityClose" @click="showTips = false"></view>
</view>
</view>
<z-paging ref="paging" :fixed="false" paging-class="paging-class px-48" :loading-full-fixed="false" :auto-show-system-loading="true" :show-scrollbar="false" v-model="dataList" @query="queryList" :default-page-size="10">
<EquityCard v-for="(item, index) in dataList" :key="index" :orderCardDetail="item" @toggle-goods-list="handleToggleGoodsList" @jump="jump" @refresh="search()" @openPay="openPay"></EquityCard>
</z-paging>
<!-- <OrderScreenContract ref="openFilter" @onConfirm="openFilterConfirm" /> -->
<!-- 支付弹框 -->
<OrderPay ref="OrderPay" @jumpSuccess="jumpSuccess" />
</view>
</template>
<script>
import order_mixins from '../../order_mixins.js'
import { interceptionMixin } from '@/mixin/index'
import ZPMixin from '@/uni_modules/z-paging/components/z-paging/js/z-paging-mixin'
import EquityCard from './EquityCard'
import PublishPopup from '@/components/PublishPopup.vue'
import dayjs from 'dayjs'
import utils from '@/utils/utils'
// import OrderScreenContract from '@/components/OrderScreenContract/index.vue'
import OrderPay from './OrderPay.vue'
export default {
name: 'OrderManagement',
mixins: [ZPMixin, interceptionMixin],
components: {
EquityCard,
PublishPopup,
// OrderScreenContract,
OrderPay
},
computed: {
orderObj() {
return order_mixins.data.orderObj || []
},
payType() {
return order_mixins.data.payType || {}
},
status() {
return order_mixins.data.status || {}
}
},
data() {
return {
itemFormObj: [
{
label: '交易参考号',
prop: 'tradeNo',
type: 'copy'
},
{
label: '支付时间',
prop: 'accountDate',
type: 'time'
},
{
label: '支付金额',
prop: 'totalFee',
type: 'price'
},
{
label: '商户名称',
prop: 'shopMerchantName'
}
],
tabList: [
{ tabName: '全部', num: 0, value: null },
{ tabName: '待补录', num: 0, value: 0 },
{ tabName: '提单失败', num: 0, value: 3 },
{ tabName: '已完成', num: 0, value: 2 }
],
tabIndex: 0,
activeIndex: 0,
customerName: '',
searchObj: {},
dataList: [],
triggered: false,
triggered1: false,
waitOrderTimer: null, // 定时器引用
tipsProps: {
tipsText: '该门店产生异常订单,请点击补录!',
showTips: true,
type: 2,
typeText: '补录订单'
},
normalOrderNoList: [],
abnormalOrderNoList: [],
abnormalCurrentPage: 1,
normalCurrentPage: 1,
abnormalPages: 1,
normalPages: 1,
checkListObj: {},
localUserInfo: null,
showTips: true
}
},
mounted() {
uni.$track.add({ eventCode: 'app_order_management' })
this.localUserInfo = uni.$storage.get('userInfo') || {}
if (!this.localUserInfo.isSuper && this.localUserInfo.loginRole != 3 && this.localUserInfo?.loginRole != 6) {
this.searchObj.transferIds = [this.localUserInfo.uuid]
}
this.search()
},
methods: {
clear() {
this.customerName = ''
this.search()
},
search() {
// 判断是不是超管 && !this.localUserInfo.isSuper
// ,不是只能筛选当前4s店的
if (!this.searchObj.merchantId) {
this.searchObj.merchantId = this.localUserInfo?.shopMerchantId
}
this.$refs.paging.reload()
this.getStatByStatus()
},
handleToggleGoodsList(data) {
this.$set(data.item, 'showAllGoodsListFlag', data.flag)
},
switchTab(index) {
this.tabIndex = index
this.searchObj.orderStatus = this.tabList[index].value
this.search()
},
openFilter() {
this.$refs.openFilter.open(this.searchObj)
},
openFilterConfirm(val) {
console.log(val)
this.searchObj = null
this.searchObj = val
console.log(this.searchObj)
this.search()
},
copyText(e) {
console.log(e)
uni.setClipboardData({
data: e,
success: () => {
uni.showToast({
title: '复制成功',
icon: 'success',
duration: 2000
})
}
})
},
tabChange(index) {
this.activeIndex = index
if (this.activeIndex === 0 && !this.normalOrderNoList.length) {
this.getTransactionSerialNumber()
}
if (this.activeIndex === 1 && !this.abnormalOrderNoList.length) {
this.getTransactionSerialNumber()
}
},
getStatByStatus() {
const localUserInfo = uni.$storage.get('userInfo')
console.log(this.searchObj, 'this.searchObj')
let params = {
merchantId: localUserInfo.shopMerchantId
}
uni.$api.equityApi
.equityStatistics(params)
.then(result => {
const labelList = ['totalOder', 'ladingOder', 'failed', 'success']
labelList.map((item, index) => {
this.tabList[index].num = result[item] ? result[item] : 0
})
console.log(this.tabList)
})
.catch(err => {
console.log(err)
})
},
pageonReachBottom() {
if (this.activeIndex === 0) {
if (this.normalPages == this.normalCurrentPage) return uni.showToast({ title: '列表已到底', icon: 'none' })
this.normalCurrentPage += 1
} else {
if (this.abnormalPages == this.abnormalCurrentPage) return uni.showToast({ title: '列表已到底', icon: 'none' })
this.abnormalCurrentPage += 1
}
this.getTransactionSerialNumber()
},
onRefresh() {
this.triggered = true
this.normalCurrentPage = 1
this.normalOrderNoList = []
this.getTransactionSerialNumber()
},
onRefresh1() {
this.triggered1 = true
this.abnormalCurrentPage = 1
this.abnormalOrderNoList = []
this.getTransactionSerialNumber()
},
getTransactionSerialNumber() {
uni.$api.boutiqueApi
.transactionSerialNumber({ currentPage: this.activeIndex === 0 ? this.normalCurrentPage : this.abnormalCurrentPage, pageSize: 10, inputOrderType: this.activeIndex + 1, inputStatus: 0 })
.then(result => {
if (this.activeIndex == 0) {
this.normalOrderNoList = [...this.normalOrderNoList, ...result.list]
this.normalPages = result.pages
this.triggered = false
this.triggered1 = false
} else {
this.abnormalOrderNoList = [...this.abnormalOrderNoList, ...result.list]
this.abnormalPages = result.pages
this.triggered = false
this.triggered1 = false
}
})
.catch(err => {
console.log(err)
})
},
queryList(pageNo, pageSize) {
const localUserInfo = uni.$storage.get('userInfo')
console.log(this.searchObj)
let params = {
pageSize,
pageNum: pageNo,
customerName: this.customerName,
merchantId: localUserInfo.shopMerchantId,
orderStatus: ''
}
uni.$api.equityApi
.equityPage(params)
.then(result => {
console.log(result)
this.$refs.paging.complete(result.data)
})
.catch(err => {
this.$refs.paging.complete(false)
console.log(err)
})
},
// 价格过滤器
priceFilter(num) {
var pow = Math.pow(10, 2)
return (Math.round((num / 100) * pow) / pow).toFixed(2)
},
formatDate(time) {
return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
},
// 选择点击事件
selectTap(index) {
this.$emit('select-tap', index)
},
// 复制订单号
copyOutTradeNo(item) {
this.$emit('copy-out-trade-no', item)
},
activeClick(item) {
if (this.checkListObj[item.tradeNo]) {
this.$delete(this.checkListObj, item.tradeNo)
} else {
this.$set(this.checkListObj, item.tradeNo, item)
}
},
cancelSelection() {
this.checkListObj = {}
this.$refs.WaitinputorderPopup.closePopup()
},
jump(name, val) {
console.log(name, val, 'jump')
this.$emit('jump', name, val)
},
openPay(item) {
this.$refs.OrderPay.open(item.id)
},
jumpSuccess(params) {
this.$emit('jump', 'OrderDetail', params)
}
}
}
</script>
<style lang="scss" scope>
.order-management {
height: 100%;
.paging-class {
height: calc(100% - #{toRpx(288)});
}
.px-48 {
padding: 0 toRpx(48);
}
.search-box {
padding: toRpx(40) toRpx(48) toRpx(0);
position: relative;
&::after {
content: '';
position: absolute;
left: 0;
top: 0;
z-index: -2;
width: 100%;
height: 100%;
opacity: 0.15;
background: linear-gradient(0deg, #94c2ff00 0%, #5294ff 100%);
}
&::before {
content: '';
position: absolute;
left: toMinusRpx(20);
top: toMinusRpx(28);
z-index: -1;
width: toRpx(136);
height: toRpx(136);
opacity: 0.6;
background: linear-gradient(-44.4deg, #94c2ff00 0%, #5294ff 100%);
filter: blur(24px);
}
.clear {
position: absolute;
right: toRpx(18);
top: toRpx(10);
height: 100%;
padding: 0 48rpx;
}
.search-input {
text-align: center;
height: toRpx(72);
border-radius: toRpx(40);
opacity: 1;
background: #f5f7fa;
.uni-input-placeholder {
color: #999ea8;
font-size: toRpx(28);
}
.placeholder {
height: 100%;
color: #999ea8;
font-family: uniicons;
display: flex;
align-items: center;
justify-content: center;
&::after {
display: block;
content: '\e654';
margin-left: 8rpx;
height: 100%;
display: flex;
align-items: center;
font-size: 36rpx;
}
}
}
}
.tab-container {
display: flex;
// justify-content: start;
position: relative;
padding-right: toRpx(48);
.tab-flex-box {
padding: toRpx(24) 0 toRpx(24) toRpx(48);
}
.flex:first-child {
display: flex;
flex: 1;
overflow-x: auto;
overflow-y: hidden;
white-space: nowrap;
-webkit-overflow-scrolling: touch;
margin-right: toRpx(20);
&::-webkit-scrollbar {
display: none;
}
}
.filter-item {
// width: toRpx(164);
height: toRpx(72);
border-radius: toRpx(16);
background: #fff;
border: toRpx(2) solid #ffffffcc;
color: #333333;
font-size: toRpx(28);
font-weight: 400;
padding: toRpx(0) toRpx(40);
flex-shrink: 0;
white-space: nowrap;
}
}
.tab-item {
// width: toRpx(164);
height: toRpx(72);
border-radius: toRpx(16);
margin-right: toRpx(20);
padding: toRpx(0) toRpx(40);
opacity: 1;
display: flex;
align-items: center;
justify-content: center;
font-size: toRpx(28);
color: #666666;
font-weight: normal;
background: #fff;
border: toRpx(2) solid #ffffffcc;
flex-shrink: 0;
&.active {
border: toRpx(2) solid #ffffff;
background: linear-gradient(180deg, #6795ff 0%, #4a84f9 100%);
box-shadow: toRpx(4) toRpx(8) toRpx(16) 0 #81a3d659;
color: #ffffff;
font-weight: bold;
transform: scale(1.05);
}
.num {
margin-left: toRpx(4);
font-size: toRpx(20);
font-weight: 500;
}
}
.waitinputorderPopup .popup-content {
.waitinputorder-tab-container {
width: toRpx(488);
border-radius: toRpx(64);
opacity: 1;
background: #f5f7fa;
}
.waitinputorder-tab-buttons {
display: flex;
background-color: #f5f5f5;
border-radius: 24rpx;
overflow: hidden;
margin-bottom: 20rpx;
}
.waitinputorder-tab-button {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
font-size: toRpx(28);
font-weight: 500;
color: #333;
position: relative;
width: toRpx(236);
height: toRpx(56);
border-radius: toRpx(40);
&.active {
background-color: #000;
color: #fff;
}
.question-icon {
margin-left: 8rpx;
opacity: 0.6;
}
}
}
.order_no_box {
height: calc(67vh - #{toRpx(364)});
.order-gap {
display: grid;
grid-template-columns: 1fr 1fr;
gap: toRpx(36);
}
.order_no_item {
border-radius: toRpx(16);
opacity: 1;
border: toRpx(2) solid #dce0e6;
padding: toRpx(24) toRpx(32);
background: #f5f7fa;
position: relative;
.message {
.item {
margin-bottom: toRpx(12);
&:last-child {
margin-bottom: 0;
}
}
.label {
color: #999ea8;
font-size: toRpx(24);
font-weight: 400;
width: toRpx(120);
margin-right: toRpx(24);
}
.value {
color: #333333;
font-size: toRpx(24);
font-weight: 400;
}
}
.checked {
position: absolute;
top: 0;
right: 0;
}
}
.checkActive {
border: toRpx(2) solid #4673ff;
background: #4673ff1a;
}
.copy-btn {
display: flex;
align-items: center;
margin-left: auto;
color: #808291;
.copy {
margin-right: toRpx(8);
margin-left: toRpx(20);
}
}
.nothing {
width: 100%;
height: toRpx(228);
flex-direction: column;
margin-top: toRpx(76);
font-size: toRpx(24);
color: #999999;
box-sizing: border-box;
&.big-height {
height: toRpx(234);
}
.icon {
width: toRpx(288);
height: toRpx(144);
margin-bottom: toRpx(4);
}
}
}
.footer-box {
width: 100%;
height: toRpx(164);
background-color: #fff;
.btn {
width: 30%;
height: toRpx(80);
border-radius: toRpx(48);
opacity: 1;
line-height: toRpx(80);
text-align: center;
color: #333333;
font-size: toRpx(32);
font-weight: 500;
}
.cancle-btn {
background: #f0f1f5;
}
.sure-btn {
color: #fff;
background: linear-gradient(0deg, #2c66f7 0%, #48a6ff 100%);
margin-left: toRpx(32);
}
}
.tips {
height: toRpx(72);
border-radius: toRpx(16);
background: #e0e8ff;
color: #2c66f7;
font-size: toRpx(28);
font-weight: 400;
padding: toRpx(0) toRpx(34);
margin-bottom: toRpx(24);
.icon-equityTip {
margin-right: toRpx(14);
}
}
}
</style>
......@@ -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) {
......
<template>
<view class="order">
<view :class="['order-box']">
<view class="common-title">客户签字</view>
<view class="box">
<scroll-view class="scroll-view" scroll-y="true">
<view class="box-content">
<view class="box-shell pt-32">
<view class="descTextTitle">尊敬的客户,您好!</view>
<view class="h3 descText">本人自愿在门店购买保险。门店已就新车投保项目及服务进行了说明,本人完全理解相关项目的服务流程及细则。</view>
</view>
<view class="box-shell">
<view class="tips descText">请在确认以上信息后,在下方的签字区内签字确认,感谢您的配合!</view>
<view class="title descTextTitle">签字处</view>
<view class="sign-box" :class="{ landscape }">
<l-signature disableScroll ref="signatureRef" :penColor="penColor" :penSize="penSize" :openSmooth="openSmooth" @touchstart="onSignatureTouch"></l-signature>
<view v-if="showPlaceHoder" class="placehoder">签字区</view>
<view @click="fullScreen" class="full_icon flex_scb sprite-icon icon-fullScreen">
<!-- <cover-image webp mode="widthFix" class="icon" src="/images/fullScreen.png" />
<cover-view class="full_text">全屏</cover-view> -->
</view>
<view @click="onClick('clear')" class="delete_icon flex_scb sprite-icon icon-sign_del">
<!-- <cover-image webp mode="widthFix " class="icon deleteIcon" src="/images/sign_del.png" /> -->
</view>
</view>
</view>
</view>
</scroll-view>
<view class="btns flex">
<view class="btn save" @click="back">稍后处理</view>
<view @click="submit" class="btn">已完成</view>
</view>
</view>
</view>
<NoticePopup ref="notice" title="重要提示" text="当前页面暂未保存,是否确认退出" type="warning"></NoticePopup>
</view>
</template>
<script>
import utils from '@/utils/utils'
import { UpdateOrderInfo, popupTypeEnum, payTypeList, titleList } from '../contant'
import NoticePopup from '@/components/NoticePopup.vue'
export default {
name: 'SignName',
components: {
NoticePopup
},
props: {
transmissionOfData: {
type: Object,
default: () => null
}
},
data() {
return {
showUpload: false,
showTips: true,
titleList,
formList: utils.deepClone(UpdateOrderInfo),
valueKey: '',
externalData: [],
popupType: 0,
baseConfigData: {},
landscape: false,
requiredList: [], // 录单设置的必填项
orderObj: {
owner: '',
phone: '',
salesType: '0',
carVin: '',
certificateNo: '',
notes: ''
},
title: 'Hello',
penColor: 'red',
penSize: 5,
url: '',
openSmooth: false,
showPlaceHoder: true
}
},
computed: {
showPayTips() {
return this.orderObj.payee == 0 && this.orderObj.payType == 7
},
userInfo() {
return uni.$storage.get('userInfo') || {}
}
},
watch: {
transmissionOfData: {
handler(newVal, oldVal) {
if (newVal) {
console.log(newVal, 'newVal')
} else {
console.log(oldVal, 'oldVal')
}
}
}
},
mounted() {
this.baseConfigData = uni.$storage.get('mock_data') || {}
this.initData()
},
methods: {
initData() {
console.log('initData', this.transmissionOfData)
const { paramsData } = this.transmissionOfData
this.getQuotationInfoById(paramsData.id)
// 埋点
// uni.$track.add({ eventCode: 'app_create_order' })
},
async getQuotationInfoById(id) {
const data = await uni.$api.equityApi.getQuotationInfoById({ id })
console.log(data, 'data')
// this.orderInfo = data
this.orderObj.id = id
this.orderObj.ownerId = data.owner.id
this.orderObj.carVin = data.owner.carVin
this.orderObj.owner = data.owner.owner
this.orderObj.phone = data.owner.phone
this.orderObj.salesType = data.owner.salesType.toString()
this.orderObj.certificateNo = data.owner.certificateNo
this.orderObj.notes = data.notes
this.updateFormSelection()
},
// 输入框失去焦点事件
inputBlur(e, val) {
console.log(e, val)
this.orderObj[val.value] = this.orderObj[val.value]
},
// 校验必填等规则
checkRequired() {
try {
const phoneRex = /^[1]([3-9])[0-9]{9}$/,
requiredArr = [],
onlyLabelItem = [],
{ orderObj } = this
this.formList.forEach(group => {
group.forEach(item => {
if (item.required === true && item.hidden !== true) {
if (item.isArray) onlyLabelItem.push(item)
else requiredArr.push(item)
}
})
})
// 遍历requiredArr,检查orderObj中是否有对应的值
for (let i = 0; i < requiredArr.length; i++) {
const item = requiredArr[i]
// 兼容嵌套customer对象的情况
let value = orderObj[item.value]
if (value === undefined || value === null || value === '') throw `${item.label}不能为空`
// 如果是customerPhone,添加phoneRex校验
if (item.value === 'phone' && !phoneRex.test(value)) throw `请输入正确的${item.label}`
}
if (orderObj.carVin) {
const vinRex = /^(?=.*[A-Za-z])[A-Za-z0-9]{17}$/
if (!vinRex.test(orderObj.carVin)) throw '请输入正确的车架号'
}
if (orderObj.certificateNo && orderObj.certificateNo.length != 18) throw '请输入正确的18位证件号'
return true
} catch (error) {
if (error)
uni.showToast({
title: error,
icon: 'none'
})
return false
}
},
// 提交
async submit() {
if (await this.checkDailyReport()) return
let params = {
id: this.orderObj.id,
notes: this.orderObj.notes || '',
owner: {
id: this.orderObj.ownerId,
owner: this.orderObj.owner,
phone: this.orderObj.phone,
carVin: this.orderObj.carVin || '',
certificateNo: this.orderObj.certificateNo || '',
salesType: this.orderObj.salesType || 0
}
}
console.log(params, 'params')
uni.showLoading({
title: '提交中...',
mask: true
})
uni.$api.equityApi
.updateCustomerInfo(params)
.then(result => {
uni.hideLoading()
console.log(result)
this.$emit('jump', 'OrderManagement', {})
})
.catch(err => {
uni.hideLoading()
})
},
back() {
// 配置弹窗按钮
this.$refs.notice.buttonsList = [
{
text: '确认退出',
type: 'default',
callback: () => {
this.transmissionOfData = null
this.$refs.notice.close()
this.$emit('jump', 'OrderManagement', {})
}
},
{
text: '继续编辑',
type: 'primary',
callback: () => {
this.$refs.notice.close()
}
}
]
// 打开弹窗
this.$refs.notice.open()
},
radioChange(val) {
console.log(val)
this.orderObj.salesType = val.detail.value.toString()
},
updateFormSelection() {
this.formList.forEach(group => {
group.forEach(item => {
if (item.value === 'salesType') {
item.current = this.orderObj.salesType
console.log('更新salesType字段:', item.current)
}
})
})
},
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]()
},
fullScreen() {
this.landscape = !this.landscape
},
onSignatureTouch(val) {
console.log(val, 'val')
// this.showPlaceHoder = val
// this.$refs.signatureRef.isEmpty
}
}
}
</script>
<style scoped lang="scss">
.order {
height: 100%;
position: relative;
&-box {
visibility: visible;
height: 100%;
}
.hide {
opacity: 0;
visibility: hidden;
}
.upload-box {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
}
.box {
height: calc(100% - #{toRpx(120)});
.scroll-view {
// height: calc(100% - #{toRpx(148)});
}
}
.box-content {
padding: 0 toRpx(48);
}
.box-shell {
width: 100%;
border-radius: toRpx(16);
background: #ffffff;
padding: toRpx(32);
margin-top: toRpx(16);
}
.btns {
position: absolute;
bottom: 0;
width: 100%;
left: 0;
padding: 24rpx 128rpx;
gap: 32rpx;
.save {
background: #3b73ff1a;
color: #4673ff;
font-size: 28rpx;
font-weight: 500;
}
}
.btn {
display: flex;
align-items: center;
justify-content: center;
width: toRpx(1130);
height: toRpx(80);
color: #fff;
border-radius: toRpx(48);
background: linear-gradient(0deg, #2c66f7 0%, #48a6ff 100%);
}
.h3 {
text-indent: 2em;
}
.descTextTitle {
font-weight: 500;
font-size: toRpx(34);
color: #333333;
line-height: toRpx(48);
margin-bottom: toRpx(20);
}
.descText {
font-size: toRpx(28);
color: #333333;
}
.title {
margin-top: toRpx(32);
margin-bottom: toRpx(24);
}
.sign-box {
position: relative;
width: 100%;
height: toRpx(600);
border-radius: toRpx(12);
background: #f4f5f7;
// 全屏样式
&.landscape {
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
border-radius: 0;
z-index: 999999;
}
}
.full_icon {
position: absolute;
right: toRpx(26);
// top: var(--fontSize16);
top: toRpx(26);
z-index: 10000;
transition: all 0.3s ease;
}
.delete_icon {
position: absolute;
right: toRpx(26);
// top: var(--fontSize16);
bottom: toRpx(26);
z-index: 10000;
}
.placehoder {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
font-size: toRpx(32);
font-weight: 500;
color: #dfdfdf;
}
</style>
......@@ -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
<template>
<view class="l-signature" ref="signatureRef" :style="[drawableStyle]">
<!-- #ifdef APP-ANDROID || APP-IOS -->
<view class="l-signature-landscape" ref="signatureLandscapeRef" v-if="landscape && url !=''"
:style="[landscapeStyle]">
<image class="l-signature-image" :style="[landscapeImageStyle]" :src="url"></image>
</view>
<!-- #endif -->
<!-- #ifdef APP-HARMONY -->
<canvas ref="signatureCanvasRef" class="l-signature__canvas"></canvas>
<!-- #endif -->
<!-- #ifndef APP -->
<canvas id="l-signature" class="l-signature__canvas" @touchstart="touchstart" @touchmove.stop="touchmove"
@touchend="touchend">
</canvas>
<!-- #endif -->
</view>
</template>
<script lang="uts" setup>
// @ts-nocheck
/**
* Signature 电子签名板组件
* @description 用于实现手写签名功能,支持多种画笔设置和手势控制
* <br>插件类型:LSignatureComponentPublicInstance
* @tutorial https://ext.dcloud.net.cn/plugin?name=lime-signature
*
* @property {string} styles 画布容器样式
* @property {string} penColor 画笔颜色
* @property {number} penSize 画笔基础粗细
* @property {string} backgroundColor 画布背景色
* @property {boolean} openSmooth 启用笔迹平滑
* @property {number} minLineWidth 最小笔触宽度
* @property {number} maxLineWidth 最大笔触宽度
* @property {number} minSpeed 最小绘制速度(像素/秒)
* @property {number} maxWidthDiffRate 宽度变化率限制
* @property {number} maxHistoryLength 撤销历史记录数
* @property {boolean} disableScroll 禁止滚动穿透
* @property {boolean} disabled 禁用签名板
* @property {boolean} landscape 横屏模式
* @event {Function} change 绘制内容变化时触发
*/
// #ifdef APP
import { Signature } from './signature.uts'
// #endif
// #ifndef APP
import { Signature } from './signature.js'
import { wrapEvent } from './utils'
// #endif
import { LimeSignatureToTempFilePathOptions, LimeSignatureToFileSuccess, LimeSignatureOptions } from '../../index.uts'
// type SignatureToFileSuccessCallback = (res : UTSJSONObject) => void
// type SignatureToFileFailCallback = (res : TakeSnapshotFail) => void
// type SignatureToFileCompleteCallback = (res : any) => void
const emit = defineEmits(['change'])
const props = defineProps({
styles: {
type: String,
default: ''
},
penColor: {
type: String,
default: 'black'
},
penSize: {
type: Number,
default: 2
},
backgroundColor: {
type: String,
default: ''
},
openSmooth: {
type: Boolean,
default: false
},
minLineWidth: {
type: Number,
default: 2
},
maxLineWidth: {
type: Number,
default: 6
},
minSpeed: {
type: Number,
default: 1.5
},
maxWidthDiffRate: {
type: Number,
default: 20
},
maxHistoryLength: {
type: Number,
default: 20
},
disableScroll: {
type: Boolean,
default: true
},
disabled: {
type: Boolean,
default: false
},
landscape: {
type: Boolean,
default: false
},
})
const drawableStyle = computed<string>(() : string => {
let style : string = ''
if (props.backgroundColor != '') {
style += `background-color: ${props.backgroundColor};`
}
if (props.styles != '') {
style += props.styles
}
return style
})
const signatureRef = ref<UniElement | null>(null)
const signatureCanvasRef = ref<UniElement | null>(null)
let signatureLandscapeRef = ref<UniElement | null>(null)
let landscapeStyle = ref<Map<string, string>>(new Map())
let landscapeImageStyle = ref<Map<string, string>>(new Map())
let isCanvasEmpty = true
let signature : Signature | null = null
let url = ref('')
// 检查并触发事件的方法
const checkAndEmitEmptyStatus = () => {
// #ifndef APP
// @ts-ignore
const isEmpty = signature?.isEmpty() ?? true
// #endif
// #ifdef APP
// @ts-ignore
const isEmpty = signature?.isEmpty ?? true
// #endif
if (isEmpty != isCanvasEmpty) {
isCanvasEmpty = isEmpty
emit('change', isCanvasEmpty)
}
}
// #ifndef APP
let canvas : HTMLCanvasElement | null = null;
const getTouch = (event : UniTouchEvent) => {
const touch = event.touches.length ? event.touches[0] : event.changedTouches[0];
return {
points: [
{
x: touch.clientX, //- rect.left,
y: touch.clientY //- rect.top
}
]
}
}
let touchstart = (e : UniTouchEvent) => {
// #ifndef WEB
signature!.canvas.emit('touchstart', getTouch(e))
// #endif
}
let touchmove = (e : UniTouchEvent) => {
// #ifndef WEB
signature!.canvas.emit('touchmove', getTouch(e))
// #endif
}
let touchend = (e : UniTouchEvent) => {
// #ifndef WEB
signature!.canvas.emit('touchend', getTouch(e))
// #endif
setTimeout(() => {
checkAndEmitEmptyStatus()
}, 0); // 绘制结束时检查
}
// #endif
const clear = () => {
signature?.clear()
checkAndEmitEmptyStatus() // 状态检查
}
const redo = () => {
signature?.redo()
checkAndEmitEmptyStatus() // 状态检查
}
const undo = () => {
signature?.undo()
checkAndEmitEmptyStatus() // 状态检查
}
const canvasToTempFilePath = (options : LimeSignatureToTempFilePathOptions) => {
const success = options.success // as SignatureToFileSuccessCallback | null
const fail = options.fail // as SignatureToFileFailCallback | null
const complete = options.complete// as SignatureToFileCompleteCallback | null
const format = options.format ?? 'png'
// #ifdef APP-ANDROID || APP-IOS
signatureRef.value?.takeSnapshot({
format,
success: (res) => {
if (props.landscape) {
url.value = res.tempFilePath;
setTimeout(() => {
signatureLandscapeRef.value?.takeSnapshot({
format,
success: (res2) => {
success?.({
tempFilePath: res2.tempFilePath,
isEmpty: signature?.isEmpty ?? false
} as LimeSignatureToFileSuccess)
}
})
}, 300)
} else {
success?.({
tempFilePath: res.tempFilePath,
isEmpty: signature?.isEmpty ?? false
} as LimeSignatureToFileSuccess)
}
},
fail: (res) => {
fail?.(res)
},
complete: (res) => {
complete?.(res)
}
} as TakeSnapshotOptions)
// #endif
// #ifdef APP-HARMONY
const image = signatureCanvasRef.value!.toDataURL()
success?.({
tempFilePath: image,
isEmpty: signature?.isEmpty ?? false
} as LimeSignatureToFileSuccess)
// #endif
// #ifndef APP
// @ts-ignore
const { backgroundColor, backgroundImage, landscape, boundingBox } = props
const { quality = 1 } = options
const flag = landscape || backgroundColor || boundingBox
const type = `image/${format}`.replace(/jpg/, 'jpeg');
const image = canvas?.toDataURL(!flag && type, !flag && quality)
if (flag) {
// @ts-ignore
// #ifdef WEB
const offCanvas = document.createElement('canvas')
// #endif
// #ifndef WEB
const offCanvas = uni.createOffscreenCanvas({ type: '2d' });
// #endif
// @ts-ignore
const pixelRatio = signature?.canvas.get('pixelRatio')
// @ts-ignore
let width = signature?.canvas.get('width')
// @ts-ignore
let height = signature?.canvas.get('height')
let x = 0
let y = 0
// @ts-ignore
const next = () => {
const size = [width, height]
if (landscape) {
size.reverse()
}
offCanvas.width = size[0] * pixelRatio
offCanvas.height = size[1] * pixelRatio
const param = [x, y, width, height, 0, 0, width, height].map(item => item * pixelRatio)
const context = offCanvas.getContext('2d')
if (landscape) {
context.translate(0, width * pixelRatio)
context.rotate(-Math.PI / 2)
}
if (backgroundColor) {
context.fillStyle = backgroundColor
context.fillRect(0, 0, width * pixelRatio, height * pixelRatio)
}
const drawImage = () => {
// @ts-ignore
// context.drawImage(image, ...param)//signature?.canvas!.get('el')
// #ifndef WEB
const img = offCanvas.createImage()
// #endif
// #ifdef WEB
const img = new Image()
// #endif
img.onload = ()=> {
context.drawImage(img, ...param)//signature?.canvas!.get('el')
success?.({
tempFilePath: offCanvas.toDataURL(type, quality),
// @ts-ignore
isEmpty: signature?.isEmpty() ?? false
} as LimeSignatureToFileSuccess)
}
img.onerror = ()=> {
success?.({
tempFilePath: image,
// @ts-ignore
isEmpty: signature?.isEmpty() ?? false
} as LimeSignatureToFileSuccess)
}
img.src = image
// #ifdef WEB
offCanvas.remove()
// #endif
}
if (backgroundImage) {
const img = new Image();
img.onload = () => {
context.drawImage(img, ...param)
drawImage()
}
img.src = backgroundImage
}
if (!backgroundImage) {
drawImage()
}
}
if (boundingBox) {
// @ts-ignore
const res = signature?.getContentBoundingBox()
width = res.width
height = res.height
x = res.startX
y = res.startY
next()
} else {
next()
}
} else {
success?.({
tempFilePath: image,
// @ts-ignore
isEmpty: signature?.isEmpty() ?? false
} as LimeSignatureToFileSuccess)
}
// #endif
}
defineExpose({
clear,
redo,
undo,
canvasToTempFilePath,
})
// #ifndef APP
// #ifdef WEB
let _touchstart, _touchmove, _touchend
// #endif
const instance = getCurrentInstance()!.proxy!;
uni.createCanvasContextAsync({
id: 'l-signature',
component: instance,
success: (context : CanvasContext) => {
const canvasContext = context.getContext('2d')!;
canvas = canvasContext.canvas;
// 处理高清屏逻辑
const dpr = uni.getDeviceInfo().devicePixelRatio ?? 1;
canvas.width = canvas.offsetWidth * dpr;
canvas.height = canvas.offsetHeight * dpr;
canvasContext.scale(dpr, dpr); // 仅需调用一次,当调用 reset 方法后需要再次 scale
signature = new Signature({
// @ts-ignore
context: canvasContext,
width: canvas.offsetWidth,
height: canvas.offsetHeight,
canvas: context,
pixelRatio: 1,
})
// signature = new Signature({el: canvas})
watchEffect(() => {
const options : LimeSignatureOptions = {
penColor: props.penColor,
openSmooth: props.openSmooth,
disableScroll: props.disableScroll,
disabled: props.disabled,
penSize: props.penSize,
minLineWidth: props.minLineWidth,
maxLineWidth: props.maxLineWidth,
minSpeed: props.minSpeed,
maxWidthDiffRate: props.maxWidthDiffRate,
maxHistoryLength: props.maxHistoryLength
}
// @ts-ignore
signature?.pen.setOption(options)
})
// #ifdef WEB
let isTouch = false
_touchstart = (event : UniMouseEvent) => {
isTouch = true
const rect = canvas?.getBoundingClientRect()
// @ts-ignore
signature!.canvas.emit('touchstart', {
points: [
{
x: event.clientX - rect.left,
y: event.clientY - rect.top
}
]
})
}
_touchmove = (event : UniMouseEvent) => {
if (!isTouch) return
const rect = canvas?.getBoundingClientRect()
// @ts-ignore
signature!.canvas.emit('touchmove', {
points: [
{
x: event.clientX - rect.left,
y: event.clientY - rect.top
}
]
})
}
_touchend = (event : UniMouseEvent) => {
isTouch = false
const rect = canvas?.getBoundingClientRect();
// @ts-ignore
signature!.canvas.emit('touchend', {
points: [
{
x: event.clientX - rect.left,
y: event.clientY - rect.top
}
]
})
setTimeout(function() {
checkAndEmitEmptyStatus()
}, 0); // 绘制结束时检查
}
canvas?.addEventListener('mousedown', _touchstart)
canvas?.addEventListener('mousemove', _touchmove)
canvas?.addEventListener('mouseup', _touchend)
// canvas?.addEventListener('mouseleave', _touchend)
// #endif
}
})
// #endif
onMounted(() => {
nextTick(() => {
setTimeout(()=>{
const width = signatureRef.value?.offsetWidth
const height = signatureRef.value?.offsetHeight
// #ifdef APP
landscapeStyle.value.set('width', `${height}px`)
landscapeStyle.value.set('height', `${width}px`)
landscapeImageStyle.value.set('width', `${width}px`)
landscapeImageStyle.value.set('height', `${height}px`)
landscapeImageStyle.value.set('transform', `rotate(-90deg) translateY(${width}px)`)
// #ifdef APP-ANDROID || APP-IOS
signature = new Signature(signatureRef.value!)
// #endif
// #ifndef APP-ANDROID || APP-IOS
signature = new Signature(signatureCanvasRef.value!)
// #endif
watchEffect(() => {
const options : LimeSignatureOptions = {
penColor: props.penColor,
openSmooth: props.openSmooth,
disableScroll: props.disableScroll,
disabled: props.disabled,
penSize: props.penSize,
minLineWidth: props.minLineWidth,
maxLineWidth: props.maxLineWidth,
minSpeed: props.minSpeed,
maxWidthDiffRate: props.maxWidthDiffRate,
maxHistoryLength: props.maxHistoryLength
}
// #ifdef APP
signature?.setOption(options)
signature?.onChange((_isEmpty: boolean)=>{
checkAndEmitEmptyStatus()
})
// #endif
})
// #endif
},300)
})
})
onUnmounted(() => {
// #ifdef WEB
canvas?.removeEventListener('mousedown', _touchstart)
canvas?.removeEventListener('mousemove', _touchmove)
canvas?.removeEventListener('mouseup', _touchend)
// canvas?.removeEventListener('mouseleave', touchend)
canvas?.remove()
// #endif
})
</script>
<style lang="scss">
/* #ifndef APP */
:host {
display: flex;
height: 100%;
}
/* #endif */
.l-signature {
flex: 1;
/* #ifndef APP */
width: 100%;
height: 100%;
/* #endif */
&__canvas {
width: 100%;
height: 100%;
}
&-landscape {
position: absolute;
pointer-events: none;
left: 1000rpx;
}
&-image {
transform-origin: 0% 0%;
}
}
</style>
\ No newline at end of file
<template>
<view class="lime-signature" v-if="show" :style="[canvasStyle, styles]" ref="limeSignature">
<!-- #ifndef APP-VUE || APP-NVUE -->
<canvas v-if="useCanvas2d" class="lime-signature__canvas" :id="canvasId" type="2d" :disableScroll="disableScroll" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd"></canvas>
<canvas v-else :disableScroll="disableScroll" class="lime-signature__canvas" :canvas-id="canvasId" :id="canvasId" :width="canvasWidth" :height="canvasHeight" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" @mousedown="touchStart" @mousemove="touchMove" @mouseup="touchEnd"></canvas>
<canvas v-if="showOffscreen" class="offscreen" canvas-id="offscreen" id="offscreen" :style="'width:' + offscreenSize[0] + 'px;height:' + offscreenSize[1] + 'px'" :width="offscreenSize[0]" :height="offscreenSize[1]"></canvas>
<view v-if="showMask" class="mask" @touchstart="touchStart" @touchmove.stop.prevent="touchMove" @touchend="touchEnd"></view>
<!-- #endif -->
<!-- #ifdef APP-VUE -->
<view :id="canvasId" :disableScroll="disableScroll" :rparam="param" :change:rparam="sign.update" :rclear="rclear" :change:rclear="sign.clear" :rundo="rundo" :rredo="rredo" :change:rredo="sign.redo" :change:rundo="sign.undo" :rsave="rsave" :rmask="rmask" :change:rsave="sign.save" :change:rmask="sign.mask" :rdestroy="rdestroy" :change:rdestroy="sign.destroy" :rempty="rempty" :change:rempty="sign.isEmpty"></view>
<!-- #endif -->
<!-- #ifdef APP-NVUE -->
<web-view src="/uni_modules/lime-signature/hybrid/html/index.html" class="lime-signature__canvas" ref="webview" @pagefinish="onPageFinish" @error="onError" @onPostMessage="onMessage"></web-view>
<!-- #endif -->
</view>
</template>
<script>
/**
* Signature 电子签名板组件
* @description 用于实现手写签名功能,支持多种画笔设置和手势控制
* <br>插件类型:LSignatureComponentPublicInstance
* @tutorial https://ext.dcloud.net.cn/plugin?name=lime-signature
*
* @property {string} styles 画布容器样式
* @property {string} penColor 画笔颜色
* @property {number} penSize 画笔基础粗细
* @property {string} backgroundColor 画布背景色
* @property {boolean} openSmooth 启用笔迹平滑
* @property {number} minLineWidth 最小笔触宽度
* @property {number} maxLineWidth 最大笔触宽度
* @property {number} minSpeed 最小绘制速度(像素/秒)
* @property {number} maxWidthDiffRate 宽度变化率限制
* @property {number} maxHistoryLength 撤销历史记录数
* @property {boolean} disableScroll 禁止滚动穿透
* @property {boolean} disabled 禁用签名板
* @property {boolean} landscape 横屏模式
* @event {Function} change 绘制内容变化时触发
*/
// #ifndef APP-NVUE
import { canIUseCanvas2d, wrapEvent, requestAnimationFrame, sleep, isTransparent } from './utils'
import { Signature } from './signature.js'
// import {Signature} from '@signature';
import { uniContext, createImage, toDataURL } from './context'
// #endif
import props from './props'
import { base64ToPath, getRect } from './utils'
export default {
props,
// emits: ['change'],
data() {
return {
canvasWidth: null,
canvasHeight: null,
offscreenWidth: null,
offscreenHeight: null,
useCanvas2d: true,
show: true,
offscreenStyles: '',
showMask: false,
showOffscreen: false,
isPC: false,
isCanvasEmpty: true,
// #ifdef APP-PLUS
rclear: 0,
rdestroy: 0,
rundo: 0,
rredo: 0,
rsave: JSON.stringify({
n: 0,
fileType: 'png',
quality: 1,
destWidth: 0,
destHeight: 0
}),
rmask: JSON.stringify({
n: 0,
destWidth: 0,
destHeight: 0
}),
rempty: 0,
risEmpty: true,
toDataURL: null,
tempFilePath: []
// #endif
}
},
computed: {
canvasId() {
// #ifdef VUE2
return `lime-signature${this._uid}`
// #endif
// #ifdef VUE3
return `lime-signature${this._.uid}`
// #endif
},
offscreenId() {
return this.canvasId + 'offscreen'
},
offscreenSize() {
const { offscreenWidth, offscreenHeight } = this
return this.landscape ? [offscreenHeight, offscreenWidth] : [offscreenWidth, offscreenHeight]
},
canvasStyle() {
const { canvasWidth, canvasHeight, backgroundColor } = this
return {
width: canvasWidth && canvasWidth + 'px',
height: canvasHeight && canvasHeight + 'px',
background: backgroundColor
}
},
param() {
const { penColor, penSize, backgroundColor, backgroundImage, landscape, boundingBox, openSmooth, minLineWidth, maxLineWidth, minSpeed, maxWidthDiffRate, maxHistoryLength, disableScroll, disabled } = this
return JSON.parse(
JSON.stringify({
penColor,
penSize,
backgroundColor,
backgroundImage,
landscape,
boundingBox,
openSmooth,
minLineWidth,
maxLineWidth,
minSpeed,
maxWidthDiffRate,
maxHistoryLength,
disableScroll,
disabled
})
)
}
},
// #ifdef APP-NVUE
watch: {
param(v) {
this.$refs.webview.evalJS(`update(${JSON.stringify(v)})`)
}
},
// #endif
// #ifndef APP-PLUS
created() {
const { platform } = uni.getSystemInfoSync()
this.isPC = /windows|mac/.test(platform)
this.useCanvas2d = this.type == '2d' && canIUseCanvas2d() && !this.isPC
// #ifndef H5
this.showMask = this.isPC
// #endif
},
// #endif
// #ifndef APP-PLUS
async mounted() {
if (this.beforeDelay) {
await sleep(this.beforeDelay)
}
const config = await this.getContext()
this.signature = new Signature(config)
this.canvasEl = this.signature.canvas.get('el')
this.offscreenWidth = this.canvasWidth = this.signature.canvas.get('width')
this.offscreenHeight = this.canvasHeight = this.signature.canvas.get('height')
this.stopWatch = this.$watch(
'param',
v => {
this.signature.pen.setOption(v)
},
{
immediate: true
}
)
},
// #endif
// #ifndef APP-PLUS
// #ifdef VUE3
beforeUnmount() {
this.stopWatch && this.stopWatch()
this.signature.destroy()
this.signature = null
this.show = false
// #ifdef APP-VUE || APP-NVUE
this.rdestroy++
// #endif
},
// #endif
// #ifdef VUE2
beforeDestroy() {
this.stopWatch && this.stopWatch()
this.signature.destroy()
this.show = false
this.signature = null
// #ifdef APP-VUE || APP-NVUE
this.rdestroy++
// #endif
},
// #endif
// #endif
methods: {
checkAndEmitEmptyStatus() {
setTimeout(() => {
// #ifdef APP-VUE || APP-NVUE
const isEmpty = this.risEmpty
// #endif
// #ifndef APP-VUE || APP-NVUE
const isEmpty = this.signature?.isEmpty() ?? true
// #endif
if (isEmpty != this.isCanvasEmpty) {
this.isCanvasEmpty = isEmpty
this.$emit('change', isEmpty)
}
}, 0)
},
// #ifdef MP-QQ
// toJSON() { return this },
// #endif
// #ifdef APP-PLUS
onPageFinish() {
this.$refs.webview.evalJS(`update(${JSON.stringify(this.param)})`)
},
onMessage(e = {}) {
const {
detail: {
data: [res]
}
} = e
if (res.event?.save) {
this.toDataURL = res.event.save
}
if (res.event?.changeSize) {
const { width, height } = res.event.changeSize
}
if (res.event.hasOwnProperty('isEmpty')) {
this.risEmpty = res.event.isEmpty
this.checkAndEmitEmptyStatus()
}
if (res.event?.file) {
this.tempFilePath.push(res.event.file)
if (this.tempFilePath.length > 7) {
this.tempFilePath.shift()
}
return
}
if (res.event?.success) {
if (res.event.success) {
this.tempFilePath.push(res.event.success)
if (this.tempFilePath.length > 8) {
this.tempFilePath.shift()
}
this.toDataURL = this.tempFilePath.join('')
this.tempFilePath = []
} else {
this.$emit('fail', 'canvas no data')
}
return
}
},
// #endif
redo() {
// #ifdef APP-VUE || APP-NVUE
this.rredo += 1
// #endif
// #ifdef APP-NVUE
this.$refs.webview.evalJS(`redo()`)
// #endif
// #ifndef APP-VUE
if (this.signature) {
this.signature.redo()
}
this.checkAndEmitEmptyStatus()
// #endif
},
restore() {
this.redo()
},
undo() {
// #ifdef APP-VUE || APP-NVUE
this.rundo += 1
// #endif
// #ifdef APP-NVUE
this.$refs.webview.evalJS(`undo()`)
// #endif
// #ifndef APP-VUE
if (this.signature) this.signature.undo()
this.checkAndEmitEmptyStatus()
// #endif
},
clear() {
// #ifdef APP-VUE || APP-NVUE
this.rclear += 1
// #endif
// #ifdef APP-NVUE
this.$refs.webview.evalJS(`clear()`)
// #endif
// #ifndef APP-VUE
if (this.signature) this.signature.clear()
this.checkAndEmitEmptyStatus()
// #endif
},
isEmpty() {
// #ifdef APP-NVUE
this.$refs.webview.evalJS(`isEmpty()`)
// #endif
// #ifdef APP-VUE || APP-NVUE
this.rempty += 1
// #endif
// #ifndef APP-VUE || APP-NVUE
return this.signature.isEmpty()
// #endif
},
async canvasToMaskPath(param = {}) {
const isEmpty = this.isEmpty()
// #ifdef APP-NVUE
this.$refs.webview.evalJS(`mask(${JSON.stringify(param)})`)
// #endif
// #ifdef APP-VUE || APP-NVUE
const stopURLWatch = this.$watch('toDataURL', (v, n) => {
if (v && v !== n) {
// if(param.pathType == 'url') {
base64ToPath(v).then(res => {
param.success({
tempFilePath: res,
isEmpty: this.risEmpty
})
})
// } else {
// param.success({tempFilePath: v,isEmpty: this.risEmpty })
// }
this.toDataURL = ''
}
stopURLWatch && stopURLWatch()
})
const { fileType, quality } = param
const rmask = JSON.parse(this.rmask)
rmask.n++
rmask.destWidth = param.destWidth ?? 0
rmask.destHeight = param.destHeight ?? 0
// rmask.fileType = fileType
// rmask.quality = quality
this.rmask = JSON.stringify(rmask)
// #endif
// #ifndef APP-VUE || APP-NVUE
this.showOffscreen = true
let width = this.signature.canvas.get('width')
let height = this.signature.canvas.get('height')
let pixelRatio = this.pixelRatio || uni.getSystemInfoSync().pixelRatio
if (this.useCanvas2d) {
this.offscreenWidth = width * pixelRatio
this.offscreenHeight = height * pixelRatio
} else {
this.offscreenWidth = width
this.offscreenHeight = height
}
await sleep(100)
const context = uni.createCanvasContext('offscreen', this)
const size = Math.max(this.offscreenWidth, this.offscreenHeight)
const success = success => param.success && param.success(success)
const fail = fail => param.fail && param.fail(fail)
this.signature.pen.getMaskedImageData(imageData => {
let canvasPutImageData = (options, comp) => {
if (uni.canvasPutImageData) {
uni.canvasPutImageData(options, comp)
} else if (context.putImageData) {
context.putImageData(options)
}
}
canvasPutImageData(
{
canvasId: 'offscreen',
x: 0,
y: 0,
width: width,
height: height,
data: imageData,
fail(err) {
fail(err)
},
success: re => {
toDataURL('offscreen', this, param).then(res => {
context.restore()
context.clearRect(0, 0, size, size)
this.offscreenWidth = width
this.offscreenHeight = height
this.showOffscreen = false
success({
tempFilePath: res,
isEmpty
})
})
}
},
this
)
})
// #endif
},
canvasToTempFilePath(param = {}) {
const isEmpty = this.isEmpty()
// #ifdef APP-NVUE
this.$refs.webview.evalJS(`save(${JSON.stringify(param)})`)
// #endif
// #ifdef APP-VUE || APP-NVUE
const stopURLWatch = this.$watch('toDataURL', (v, n) => {
if (v && v !== n) {
if (this.preferToDataURL) {
param.success({
tempFilePath: v,
isEmpty: this.risEmpty
})
} else {
base64ToPath(v).then(res => {
param.success({
tempFilePath: res,
isEmpty: this.risEmpty
})
})
}
this.toDataURL = ''
}
stopURLWatch && stopURLWatch()
})
const { fileType, quality } = param
const rsave = JSON.parse(this.rsave)
rsave.n++
rsave.fileType = fileType
rsave.quality = quality
rsave.destWidth = param.destWidth ?? 0
rsave.destHeight = param.destHeight ?? 0
this.rsave = JSON.stringify(rsave)
// #endif
// #ifndef APP-VUE || APP-NVUE
const useCanvas2d = this.useCanvas2d
const success = success => param.success && param.success(success)
const fail = err => param.fail && param.fail(err)
const { canvas } = this.signature.canvas.get('el')
const { backgroundColor, landscape, boundingBox } = this
let width = this.signature.canvas.get('width')
let height = this.signature.canvas.get('height')
let x = 0
let y = 0
const devtools = uni.getSystemInfoSync().platform == 'devtools'
let preferToDataURL = this.preferToDataURL
let scale = 1
// #ifdef MP-TOUTIAO
scale = devtools ? uni.getSystemInfoSync().pixelRatio : scale
// 由于抖音不支持canvasToTempFilePath故优先使用createOffscreenCanvas
preferToDataURL = true
// #endif
const canvasToTempFilePath = async image => {
const createCanvasContext = () => {
const useOffscreen = useCanvas2d && !!uni.createOffscreenCanvas && preferToDataURL
if (useOffscreen && !devtools) {
const offCanvas = uni.createOffscreenCanvas({
type: '2d'
})
offCanvas.width = this.offscreenSize[0] * scale
offCanvas.height = this.offscreenSize[1] * scale
const context = offCanvas.getContext('2d')
return [context, offCanvas]
} else {
const context = uni.createCanvasContext('offscreen', this)
return [context]
}
}
if ((boundingBox && !this.isPC) || landscape || (backgroundColor && !isTransparent(backgroundColor))) {
this.showOffscreen = true
await sleep(100)
const [context, offCanvas] = createCanvasContext()
context.save()
context.setTransform(1, 0, 0, 1, 0, 0)
if (landscape) {
context.translate(0, width * scale)
context.rotate(-Math.PI / 2)
}
if (backgroundColor && !isTransparent(backgroundColor)) {
context.fillStyle = backgroundColor
context.fillRect(0, 0, width, height)
}
if (offCanvas) {
const img = canvas.createImage()
img.src = image
img.onload = () => {
context.drawImage(img, 0, 0, width * scale, height * scale)
const tempFilePath = offCanvas.toDataURL()
this.showOffscreen = false
success({
tempFilePath,
isEmpty
})
}
} else {
context.drawImage(image, 0, 0, width * scale, height * scale)
context.draw(false, () => {
toDataURL('offscreen', this, param).then(res => {
const size = Math.max(width, height)
context.restore()
context.clearRect(0, 0, size, size)
this.showOffscreen = false
success({
tempFilePath: res,
isEmpty
})
})
})
}
} else {
success({
tempFilePath: image,
isEmpty
})
}
}
const next = async () => {
if (this.offscreenWidth != width || this.offscreenHeight != height) {
this.offscreenWidth = width
this.offscreenHeight = height
await sleep(100)
}
// #ifndef MP-WEIXIN
const param = {
x,
y,
width,
height,
canvas,
preferToDataURL
}
// #endif
// #ifdef MP-WEIXIN
const param = {
x,
y,
width,
height,
canvas: useCanvas2d ? canvas : null,
preferToDataURL
}
// #endif
toDataURL(this.canvasId, this, param).then(canvasToTempFilePath).catch(fail)
}
// PC端小程序获取不到 ImageData 数据,长度为0
if (boundingBox && !this.isPC) {
this.signature.getContentBoundingBox(async res => {
this.offscreenWidth = width = res.width
this.offscreenHeight = height = res.height
x = res.startX
y = res.startY
next()
})
} else {
next()
}
// #endif
},
// #ifndef APP-PLUS
getContext() {
return getRect(`#${this.canvasId}`, {
context: this,
type: this.useCanvas2d ? 'fields' : 'boundingClientRect'
}).then(res => {
if (res) {
let { width, height, node: canvas, left, top, right } = res
let pixelRatio = this.pixelRatio ?? uni.getSystemInfoSync().pixelRatio
let context
if (canvas) {
context = canvas.getContext('2d')
canvas.width = width * pixelRatio
canvas.height = height * pixelRatio
} else {
pixelRatio = 1
context = uniContext(this.canvasId, this)
canvas = {
getContext: type => (type == '2d' ? context : null),
createImage,
toDataURL: () => toDataURL(this.canvasId, this),
requestAnimationFrame
}
}
// 支付宝小程序 使用stroke有个默认背景色
context.clearRect(0, 0, width, height)
return {
left,
top,
right,
width,
height,
context,
canvas,
pixelRatio
}
}
})
},
getTouch(e) {
if (this.isPC && this.canvasRect) {
if (!e.touches) return []
e.touches = [...e.touches].map(item => {
return {
...item,
x: item.clientX - this.canvasRect.left,
y: item.clientY - this.canvasRect.top
}
})
}
return e
},
touchStart(e) {
if (!this.canvasEl) return
this.isStart = true
// 微信小程序PC端不支持事件,使用这方法模拟一下
if (this.isPC) {
getRect(`#${this.canvasId}`, {
context: this
}).then(res => {
this.canvasRect = res
this.canvasEl.dispatchEvent('touchstart', wrapEvent(this.getTouch(e)))
})
return
}
this.canvasEl.dispatchEvent('touchstart', wrapEvent(e))
},
touchMove(e) {
if (!this.canvasEl || (!this.isStart && this.canvasEl)) return
this.canvasEl.dispatchEvent('touchmove', wrapEvent(this.getTouch(e)))
},
touchEnd(e) {
if (!this.canvasEl) return
this.isStart = false
this.canvasEl.dispatchEvent('touchend', wrapEvent(e))
this.checkAndEmitEmptyStatus()
}
// #endif
}
}
</script>
<!-- #ifdef APP-VUE -->
<script module="sign" lang="renderjs">
import sign from './render'
export default sign
</script>
<!-- #endif -->
<style lang="scss">
.lime-signature,
.lime-signature__canvas {
/* #ifndef APP-NVUE */
position: relative;
width: 100%;
height: 100%;
/* #endif */
/* #ifdef APP-NVUE */
flex: 1;
/* #endif */
}
.mask {
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
}
.offscreen {
position: fixed;
top: 0;
// left: 0;
pointer-events: none;
// background: rgba(0,255,0,0.5);
left: 9999px;
}
</style>
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
function t(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,n)}return i}function e(e){for(var i=1;arguments.length>i;i++){var n=null!=arguments[i]?arguments[i]:{};i%2?t(Object(n),!0).forEach((function(t){r(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):t(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function i(t){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i(t)}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){for(var i=0;e.length>i;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}function a(t,e,i){return e&&o(t.prototype,e),i&&o(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t}function r(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&u(t,e)}function h(t){return h=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},h(t)}function u(t,e){return u=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t},u(t,e)}function c(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function l(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var i,n=h(t);if(e){var o=h(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return c(this,i)}}var v=function(t){var e=i(t);return null!==t&&"object"===e||"function"===e},f={}.toString,d=function(t,e){return f.call(t)==="[object "+e+"]"},p=function(t){return d(t,"String")},y=function(t){return d(t,"Number")},g=function(t){return d(t,"Function")},m=function(){function t(){n(this,t),this.__events=void 0,this.__events={}}return a(t,[{key:"on",value:function(t,e){if(t&&e){var i=this.__events[t]||[];i.push(e),this.__events[t]=i}}},{key:"emit",value:function(t,e){var i=this;if(v(t)&&(t=(e=t)&&e.type),t){var n=this.__events[t];n&&n.length&&n.forEach((function(t){t.call(i,e)}))}}},{key:"off",value:function(t,e){var i=this.__events,n=i[t];if(n&&n.length)if(e)for(var o=0,a=n.length;a>o;o++)n[o]===e&&(n.splice(o,1),o--);else delete i[t]}},{key:"getEvents",value:function(){return this.__events}}]),t}(),x=function(t){s(i,m);var e=l(i);function i(t,o){var a;return n(this,i),(a=e.call(this)).context=void 0,a.canvas=void 0,a.attrs=void 0,a.isCanvasElement=void 0,a.context=t,a.canvas=o.canvas||t.canvas||{width:o.width||0,height:o.height||0},a.attrs=o||{},a.isCanvasElement=!0,a}return a(i,[{key:"width",get:function(){return this.canvas.width},set:function(t){this.canvas.width=t}},{key:"height",get:function(){return this.canvas.height},set:function(t){this.canvas.height=t}},{key:"getContext",value:function(){return this.context}},{key:"getBoundingClientRect",value:function(){var t=this.attrs||{},e=t.top,i=t.right,n=t.width,o=t.height,a=t.left,r=t.bottom;return{top:void 0===e?0:e,width:void 0===n?0:n,right:void 0===i?0:i,height:void 0===o?0:o,bottom:void 0===r?0:r,left:void 0===a?0:a}}},{key:"setAttribute",value:function(t,e){this.attrs[t]=e}},{key:"addEventListener",value:function(t,e){this.on(t,e)}},{key:"removeEventListener",value:function(t,e){this.off(t,e)}},{key:"dispatchEvent",value:function(t,e){this.emit(t,e)}}]),i}();var w=function(t,e){return t?function(t){if(!t)return!1;if(1!==t.nodeType||!t.nodeName||"canvas"!==t.nodeName.toLowerCase())return!1;var e=!1;try{t.addEventListener("eventTest",(function(){e=!0})),t.dispatchEvent(new Event("eventTest"))}catch(t){e=!1}return e}(t.canvas)?t.canvas:new x(t,e):null};function b(t,e){try{return t.currentStyle?t.currentStyle[e]:document.defaultView&&document.defaultView.getComputedStyle(t,null).getPropertyValue(e)}catch(t){return{width:300,height:150}[e]}}function k(t,e){var i=e.get("el");if(!i)return t;var n=i.getBoundingClientRect(),o=n.top,a=void 0===o?0:o,r=n.left,s=void 0===r?0:r,h=parseFloat(b(i,"padding-left"))||0,u=parseFloat(b(i,"padding-top"))||0;return{x:t.x-s-h,y:t.y-a-u}}function _(t,e){var i=e.get("landscape");if(!i)return t;if(g(i))return i(t,e);var n=e.get("height");return{x:t.y,y:n-t.x}}var E=function(t,e){var i=t.touches;if(!i||!i.length)return[_(k({x:t.clientX,y:t.clientY},e),e)];i.length||(i=t.changedTouches||[]);for(var n=[],o=0,a=i.length;a>o;o++){var r=i[o],s=r.x,h=r.y,u=r.clientX,c=r.clientY,l=void 0;l=y(s)||y(h)?{x:s,y:h}:k({x:u,y:c},e),n.push(_(l,e))}return n},L=function(t,e){var i=e.x-t.x,n=e.y-t.y;return Math.abs(i)>Math.abs(n)?i>0?"right":"left":n>0?"down":"up"},M=function(t,e){var i=Math.abs(e.x-t.x),n=Math.abs(e.y-t.y);return Math.sqrt(i*i+n*n)},P=function(){function t(e){var i=this,o=e.canvas,a=e.el;n(this,t),this.processEvent=void 0,this.canvas=void 0,this.startTime=0,this.endTime=0,this.startPoints=null,this.startDistance=0,this.center=null,this.pressTimeout=void 0,this.eventType=null,this.direction=null,this.lastMoveTime=0,this.prevMovePoints=null,this.prevMoveTime=0,this.lastMovePoints=null,this.pinch=!1,this._click=function(t){var e=E(t,i.canvas);t.points=e,i.emitEvent("click",t)},this._start=function(t){var e,n,o=E(t,i.canvas);o&&(t.points=o,i.emitEvent("touchstart",t),i.reset(),i.startTime=Date.now(),i.startPoints=o,o.length>1?(i.startDistance=M(o[0],o[1]),i.center={x:(e=o[0]).x+((n=o[1]).x-e.x)/2,y:e.y+(n.y-e.y)/2}):i.pressTimeout=setTimeout((function(){var e="press",n="none";t.direction=n,i.emitStart(e,t),i.emitEvent(e,t),i.eventType=e,i.direction=n}),250))},this._move=function(t){var e=E(t,i.canvas);if(e){t.points=e,i.emitEvent("touchmove",t);var n=i.startPoints;if(n)if(e.length>1){var o=i.startDistance,a=M(e[0],e[1]);t.zoom=a/o,t.center=i.center,i.emitStart("pinch",t),i.emitEvent("pinch",t)}else{var r=e[0].x-n[0].x,s=e[0].y-n[0].y,h=i.direction||L(n[0],e[0]);i.direction=h;var u=i.getEventType(e);t.direction=h,t.deltaX=r,t.deltaY=s,i.emitStart(u,t),i.emitEvent(u,t);var c=i.lastMoveTime,l=Date.now();l-c>0&&(i.prevMoveTime=c,i.prevMovePoints=i.lastMovePoints,i.lastMoveTime=l,i.lastMovePoints=e)}}},this._end=function(t){var e=E(t,i.canvas);t.points=e,i.emitEnd(t),i.emitEvent("touchend",t);var n=i.lastMoveTime;if(100>Date.now()-n){var o=n-(i.prevMoveTime||i.startTime);if(o>0){var a=i.prevMovePoints||i.startPoints,r=i.lastMovePoints;if(!a||!r)return;var s=M(a[0],r[0])/o;s>.3&&(t.velocity=s,t.direction=L(a[0],r[0]),i.emitEvent("swipe",t))}}i.reset();var h=t.touches;h&&h.length>0&&i._start(t)},this._cancel=function(t){i.emitEvent("touchcancel",t),i.reset()},this.canvas=o,this.delegateEvent(a),this.processEvent={}}return a(t,[{key:"delegateEvent",value:function(t){t.addEventListener("click",this._click),t.addEventListener("touchstart",this._start),t.addEventListener("touchmove",this._move),t.addEventListener("touchend",this._end),t.addEventListener("touchcancel",this._cancel)}},{key:"emitEvent",value:function(t,e){this.canvas.emit(t,e)}},{key:"getEventType",value:function(t){var e,i=this.eventType,n=this.startTime,o=this.startPoints;if(i)return i;var a=this.canvas.__events.pan;if(a&&a.length){var r=Date.now();if(!o)return;e=r-n>250&&10>M(o[0],t[0])?"press":"pan"}else e="press";return this.eventType=e,e}},{key:"enable",value:function(t){this.processEvent[t]=!0}},{key:"isProcess",value:function(t){return this.processEvent[t]}},{key:"emitStart",value:function(t,e){this.isProcess(t)||(this.enable(t),this.emitEvent("".concat(t,"start"),e))}},{key:"emitEnd",value:function(t){}},{key:"clearPressTimeout",value:function(){this.pressTimeout&&(clearTimeout(this.pressTimeout),this.pressTimeout=null)}},{key:"reset",value:function(){this.clearPressTimeout(),this.startTime=0,this.startPoints=null,this.startDistance=0,this.direction=null,this.eventType=null,this.pinch=!1,this.prevMoveTime=0,this.prevMovePoints=null,this.lastMoveTime=0,this.lastMovePoints=null}}]),t}(),T=function(t){s(o,m);var e=l(o);function o(t){var i;n(this,o),(i=e.call(this))._attrs={},i._isWindow=void 0,i._attrs=Object.assign({},t),i._isWindow="undefined"!=typeof window,i._initPixelRatio(),i._initCanvas();return["createImage","toDataURL","requestAnimationFrame"].forEach((function(e){i._initAttrs(e,t.canvas||i.get("el"))})),i}return a(o,[{key:"get",value:function(t){return this._attrs[t]}},{key:"set",value:function(t,e){this._attrs[t]=e}},{key:"_initAttrs",value:function(t,e){var i=this;if(!this.get(t)){this.set(t,(function(){return e[t]?e[t].apply(e,arguments):i._isWindow?window[t]?(n=window)[t].apply(n,arguments):"createImage"==t?new Image:null:void 0;var n}))}}},{key:"_initCanvas",value:function(){var t,e,i=this.get("el"),n=this.get("context");if(!i&&!n)throw Error("请指定 id、el 或 context!");t=i?p(i)?(e=i)?document.getElementById(e):null:i:w(n,this._attrs),n&&t&&!t.getContext&&(t.getContext=function(){return n});var o=this.get("width")||function(t){var e=b(t,"width");return"auto"===e&&(e=t.offsetWidth),parseFloat(e)}(t)||t.width,a=this.get("height")||function(t){var e=b(t,"height");return"auto"===e&&(e=t.offsetHeight),parseFloat(e)}(t)||t.height;this.set("canvas",this),this.set("el",t),this.set("context",n||t.getContext("2d")),this.changeSize(o,a);var r=new P({canvas:this,el:t,parent:this.get("parent")});this.set("eventController",r)}},{key:"_initPixelRatio",value:function(){this.get("pixelRatio")||this.set("pixelRatio",window&&window.devicePixelRatio||1)}},{key:"changeSize",value:function(t,e){var n,o=this.get("pixelRatio"),a=this.get("el");(a.style&&(a.style.width=t+"px",a.style.height=e+"px"),(n=a)&&"object"===i(n)&&(1===n.nodeType&&n.nodeName||n.isCanvasElement))&&(a.width=t*o,a.height=e*o,1!==o&&this.get("context").scale(o,o));this.set("width",t),this.set("height",e)}},{key:"destroy",value:function(){if(!this.get("destroyed")){var t=this.get("el");t.width=0,t.height=0,this.clear(),this._attrs={},this.set("destroyed",!0)}}},{key:"clear",value:function(){}},{key:"isDestroyed",value:function(){return this.get("destroyed")}}]),o}();var S={penColor:"black",backgroundColor:"",openSmooth:!0,penSize:2,minLineWidth:2,maxLineWidth:6,minSpeed:1.5,maxWidthDiffRate:20,maxHistoryLength:20},D=null,O=function(){function t(e){var i=this;n(this,t),this.canAddHistory=!0,this.points=[],this.historyList=[],this.undoneList=[],this.canvas=void 0,this._isEmpty=!0,this.active=!1,this.getLineWidth=function(t){var e=i.get("options"),n=e.minSpeed,o=e.minLineWidth,a=i.getMaxLineWidth();return Math.min(Math.max(a-(a-o)*t/Math.max(Math.min(n,10),1),o),a)},this.drawTrapezoid=function(t,e,n,o){var a=i.get("context");a.beginPath(),a.moveTo(Number(t.x.toFixed(1)),Number(t.y.toFixed(1))),a.lineTo(Number(e.x.toFixed(1)),Number(e.y.toFixed(1))),a.lineTo(Number(n.x.toFixed(1)),Number(n.y.toFixed(1))),a.lineTo(Number(o.x.toFixed(1)),Number(o.y.toFixed(1))),a.fillStyle=i.get("options").penColor,a.fill(),a.draw&&a.draw(!0)},this.drawNoSmoothLine=function(t,e){e.lastX=t.x+.5*(e.x-t.x),e.lastY=t.y+.5*(e.y-t.y),"number"==typeof t.lastX&&i.drawCurveLine(t.lastX,t.lastY,t.x,t.y,e.lastX,e.lastY,i.getMaxLineWidth())},this.drawCurveLine=function(t,e,n,o,a,r,s){s=Number(s.toFixed(1));var h=i.get("context");h.lineWidth=s,h.beginPath(),h.moveTo(Number(t.toFixed(1)),Number(e.toFixed(1))),h.quadraticCurveTo(Number(n.toFixed(1)),Number(o.toFixed(1)),Number(a.toFixed(1)),Number(r.toFixed(1))),h.stroke(),h.draw&&h.draw(!0)},this.getRadianData=function(t,e,i,n){var o=i-t,a=n-e;if(0===o)return{val:0,pos:-1};if(0===a)return{val:0,pos:1};var r=Math.abs(Math.atan(a/o));return i>t&&e>n||t>i&&n>e?{val:r,pos:1}:{val:r,pos:-1}},this.getRadianPoints=function(t,e,i,n){if(0===t.val)return 1===t.pos?[{x:e,y:i+n},{x:e,y:i-n}]:[{y:i,x:e+n},{y:i,x:e-n}];var o=Math.sin(t.val)*n,a=Math.cos(t.val)*n;return 1===t.pos?[{x:e+o,y:i+a},{x:e-o,y:i-a}]:[{x:e+o,y:i-a},{x:e-o,y:i+a}]},this.drawSmoothLine=function(t,e){var n=e.x-t.x,o=e.y-t.y;if(Math.abs(n)+Math.abs(o)>2?(e.lastX1=t.x+.3*n,e.lastY1=t.y+.3*o,e.lastX2=t.x+.7*n,e.lastY2=t.y+.7*o):(e.lastX1=e.lastX2=t.x+.5*n,e.lastY1=e.lastY2=t.y+.5*o),e.perLineWidth=(t.lineWidth+e.lineWidth)/2,"number"==typeof t.lastX1){if(i.drawCurveLine(t.lastX2,t.lastY2,t.x,t.y,e.lastX1,e.lastY1,e.perLineWidth),t.isFirstPoint)return;if(t.lastX1===t.lastX2&&t.lastY1===t.lastY2)return;var a=i.getRadianData(t.lastX1,t.lastY1,t.lastX2,t.lastY2),r=i.getRadianPoints(a,t.lastX1,t.lastY1,t.perLineWidth/2),s=i.getRadianPoints(a,t.lastX2,t.lastY2,e.perLineWidth/2);i.drawTrapezoid(r[0],s[0],s[1],r[1])}else e.isFirstPoint=!0},this.addHistory=function(){var t=i.get("options").maxHistoryLength;if(t&&i.canAddHistory)if(i.canAddHistory=!1,i.get("createImage")){var e=null;e=i.get("createImage")();var n=i.get("toDataURL")&&i.get("toDataURL")();p(n)?e.src=n:n.then((function(t){e.src=t})),e.onload=function(){var n=D;D=e,i.historyList.push(n),i.historyList=i.historyList.slice(-t)}}else i.historyList.length++},this.drawByImage=function(t){var e=i.get("context"),n=i.get("width"),o=i.get("height");e.clearRect(0,0,n,o);try{t&&e.drawImage(t,0,0,n,o),e.draw&&e.draw(!0)}catch(t){i.historyList.length=0}},this.isEmpty=function(){return i.get("options").maxHistoryLength>0?0===i.historyList.length:i._isEmpty},this.clear=function(){if(!i.get("options").disabled){var t=i.get("context");t.clearRect(0,0,i.get("width"),i.get("height")),t.draw&&t.draw(),i._isEmpty=!0,D=null,i.historyList.length=0}},this.undo=function(){if(!i.get("options").disabled&&(0===i.get("options").maxHistoryLength&&i.clear(),i.get("createImage")&&i.historyList.length)){var t=i.historyList.pop();i.drawByImage(t),i.undoneList.push(D),D=t,i.historyList.length||i.undoneList.length||i.clear()}},this.redo=function(){if(i.undoneList.length&&!i.get("options").disabled){var t=i.undoneList.pop();i.historyList.push(D),i.drawByImage(t),D=t,i._isEmpty=!1}},this.canvas=e,this.canvas.set("pen",S),this.init()}return a(t,[{key:"getOption",value:function(){}},{key:"setOption",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=e({},t),n=i.maxLineWidth;if(n&&t.penSize&&n==S.maxLineWidth){var o=Math.max(n,t.penSize);i.maxLineWidth=o}this.canvas.set("pen",Object.assign({},S,i))}},{key:"get",value:function(t){return this.canvas.get("options"==t?"pen":t)}},{key:"init",value:function(){var t=this;this.get("context").lineCap="round",this.canvas.on("touchstart",(function(e){return t.onDrawStart(e)})),this.canvas.on("touchmove",(function(e){return t.onDrawMove(e)})),this.canvas.on("touchend",(function(e){return t.onDrawEnd(e)}))}},{key:"drawBackground",value:function(){var t=this.get("context"),e=this.get("width"),i=this.get("height"),n=this.get("options"),o=n.backgroundColor,a=n.backgroundImage;o&&(t.fillStyle=o,t.fillRect(0,0,e,i),t.draw&&t.draw(!0)),a&&this.drawByImage(a)}},{key:"getImageData",value:function(t){if(t){var e=this.get("width"),i=this.get("height"),n=this.get("el"),o="CANVAS"===n.nodeName,a=o?e:n.width,r=o?i:n.height;if(o){var s=document.createElement("canvas");s.width=e,s.height=i;var h=s.getContext("2d");h.drawImage(n,0,0,e,i);var u=h.getImageData(0,0,e,i).data;return t(u)}var c,l=this.get("context").getImageData(0,0,a,r);return v(c=l)&&g(c.then)&&g(c.catch)?(l.then((function(e){return t(e.data)})),null):t(l.data)}}},{key:"getMaskedImageData",value:function(t){if(t)return this.getImageData((function(e){for(var i=0;e.length>i;i+=4){0===e[i+3]?(e[i]=0,e[i+1]=0,e[i+2]=0):(e[i]=255,e[i+1]=255,e[i+2]=255)}return t(e)}))}},{key:"getContentBoundingBox",value:function(t){var e=this.get("pixelRatio"),i=this.get("width"),n=this.get("height"),o=this.get("el"),a="CANVAS"===o.nodeName,r=a?i:o.width,s=a?n:o.height;e=a?1:e;return this.getImageData((function(i){for(var n=Math.floor(r),o=n,a=Math.floor(s),h=0,u=0,c=0;i.length>c;c+=4){if(i[c+3]>0){var l=c/4%n,v=Math.floor(c/4/n);o=Math.min(o,l),a=Math.min(a,v),h=Math.max(h,l),u=Math.max(u,v)}}var f={width:(h-o+1)/e,height:(u-a+1)/e,startX:o/e,startY:a/e};return t&&t(f),f}))}},{key:"remove",value:function(){var t=this;this.canvas.off("touchstart",(function(e){return t.onDrawStart(e)})),this.canvas.off("touchmove",(function(e){return t.onDrawMove(e)})),this.canvas.off("touchend",(function(e){return t.onDrawEnd(e)}))}},{key:"disableScroll",value:function(t){t.preventDefault&&this.get("options").disableScroll&&t.preventDefault()}},{key:"onDrawStart",value:function(t){if(!this.get("options").disabled){this.disableScroll(t),this.undoneList.length=0;var e=t.points;if(this.active){this.canAddHistory=!0,this.get("context").strokeStyle=this.get("options").penColor;var i=e[0];this.initPoint(i.x,i.y)}}}},{key:"onDrawMove",value:function(t){if(!this.get("options").disabled&&(this.disableScroll(t),this.active)){var e=t.points[0];this.initPoint(e.x,e.y),this.onDraw()}}},{key:"onDrawEnd",value:function(t){this.active&&!this.get("options").disabled&&(this.addHistory(),this.canAddHistory=!0,this.points=[])}},{key:"onDraw",value:function(){var t=this,e=this.get("context");if(this.points.length>=2){e.lineWidth=this.get("options").penSize||2;var i=this.points.slice(-1)[0],n=this.points.slice(-2,-1)[0],o=function(){t._isEmpty=!1,t.get("options").openSmooth?t.drawSmoothLine(n,i):t.drawNoSmoothLine(n,i)};o()}}},{key:"getMaxLineWidth",value:function(){var t=this.get("options");return Math.min(t.penSize,t.maxLineWidth)}},{key:"initPoint",value:function(t,e){var i={x:t,y:e,t:Date.now()},n=this.points.slice(-1)[0];if(!n||n.t!==i.t&&(n.x!==t||n.y!==e)){if(this.get("options").openSmooth&&n){var o=this.points.slice(-2,-1)[0];if(i.distance=Math.sqrt(Math.pow(i.x-n.x,2)+Math.pow(i.y-n.y,2)),i.speed=i.distance/(i.t-n.t||.1),i.lineWidth=this.getLineWidth(i.speed),o&&o.lineWidth&&n.lineWidth){var a=(i.lineWidth-n.lineWidth)/n.lineWidth,r=this.get("options").maxWidthDiffRate/100;if(r=r>1?1:.01>r?.01:r,Math.abs(a)>r)i.lineWidth=n.lineWidth*(1+(a>0?r:-r))}}this.points.push(i),this.points=this.points.slice(-3)}}}]),t}(),W=function(){function t(e){n(this,t),this.canvas=void 0,this._ee=void 0,this.pen=void 0;var i=new T(e);i.set("parent",this),this.canvas=i,this._ee=new m,this.pen=new O(i),this.init()}return a(t,[{key:"init",value:function(){this.pen.active=!0}},{key:"destroy",value:function(){this.canvas.destroy()}},{key:"clear",value:function(){this.pen.clear()}},{key:"undo",value:function(){this.pen.undo()}},{key:"redo",value:function(){this.pen.redo()}},{key:"save",value:function(){}},{key:"getContentBoundingBox",value:function(t){return this.pen.getContentBoundingBox(t)}},{key:"getMaskedImageData",value:function(t){return this.pen.getMaskedImageData(t)}},{key:"isEmpty",value:function(){return this.pen.isEmpty()}},{key:"on",value:function(t,e){this._ee.on(t,e)}},{key:"emit",value:function(t,e){this._ee.emit(t,e)}},{key:"off",value:function(t,e){this._ee.off(t,e)}}]),t}();export default W;export{W as Signature};
// @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
<template>
<view class="signature" :class="{landscape}">
<text class="signature-text">请在此处签名</text>
<view class="signature-area" v-if="landscape">
<l-signature disableScroll ref="signatureRef" :penColor="penColor" :penSize="penSize" :key="landscape" uid="0"
:minLineWidth="2" :openSmooth="openSmooth" :boundingBox="bBox" landscape></l-signature>
</view>
<view class="signature-area" v-if="!landscape">
<l-signature disableScroll ref="signatureRef" :penColor="penColor" :penSize="penSize" :key="!landscape" uid="1"
:minLineWidth="2" :openSmooth="openSmooth" :boundingBox="bBox"></l-signature>
</view>
<view class="screen-handle" @click="change">
<!-- #ifdef APP-NVUE -->
<text>{{landscape ? '横':'竖'}}</text>
<!-- #endif -->
<!-- #ifndef APP-NVUE -->
<image class="screen-handle__image" :src="icon" mode="widthFix"></image>
<!-- #endif -->
</view>
<view class="tools">
<view class="tools-item" @tap="isShowPen = !isShowPen;">
<!-- #ifdef APP-NVUE -->
<text>设置</text>
<!-- #endif -->
<!-- #ifndef APP-NVUE -->
<image class="tools-item__image" src="https://fastly.jsdelivr.net/gh/liangei/image@latest/brush-fill.svg" mode="widthFix"></image>
<!-- #endif -->
</view>
<view class="tools-item" @tap="onClick('undo')">
<!-- #ifdef APP-NVUE -->
<text>撤消</text>
<!-- #endif -->
<!-- #ifndef APP-NVUE -->
<image class="tools-item__image" src="https://fastly.jsdelivr.net/gh/liangei/image@latest/reply-fill.svg" mode="widthFix"></image>
<!-- #endif -->
</view>
<view class="tools-item restore" @tap="onClick('restore')">
<!-- #ifdef APP-NVUE -->
<text>上一步</text>
<!-- #endif -->
<!-- #ifndef APP-NVUE -->
<image class="tools-item__image" src="https://fastly.jsdelivr.net/gh/liangei/image@latest/reply-fill.svg" mode="widthFix"></image>
<!-- #endif -->
</view>
<view class="tools-item" @tap="onClick('clear')">
<!-- #ifdef APP-NVUE -->
<text>清空</text>
<!-- #endif -->
<!-- #ifndef APP-NVUE -->
<image class="tools-item__image" src="https://fastly.jsdelivr.net/gh/liangei/image@latest/brush-2-fill.svg" mode="widthFix"></image>
<!-- #endif -->
</view>
<view class="tools-item" @tap="onClick('save')">
<!-- #ifdef APP-NVUE -->
<text>保存</text>
<!-- #endif -->
<!-- #ifndef APP-NVUE -->
<image class="tools-item__image" src="https://fastly.jsdelivr.net/gh/liangei/image@latest/save-fill.svg" mode="widthFix"></image>
<!-- #endif -->
</view>
<view class="tools-item" @tap="onClick('save2')">
<!-- #ifdef APP-NVUE -->
<text>保存</text>
<!-- #endif -->
<!-- #ifndef APP-NVUE -->
<image class="tools-item__image" src="https://fastly.jsdelivr.net/gh/liangei/image@latest/save-fill.svg" mode="widthFix"></image>
<!-- #endif -->
</view>
</view>
<uni-popup ref="popup" type="bottom" @change="isShowPen = $event.show">
<view class="popup-wrap">
<view class="popup-item">
<view class="popup-item__head">
<view class="popup-item__title">笔锋</view>
<view class="popup-item__more">
<text class="popup-item__more-text">{{openSmooth}}</text>
<switch class="popup-item__more-switch" @change="() => openSmooth = !openSmooth" :checked="openSmooth"/>
</view>
</view>
<view class="popup-item__head">
<view class="popup-item__title">包围盒</view>
<view class="popup-item__more">
<text class="popup-item__more-text">{{bBox}}</text>
<switch class="popup-item__more-switch" @change="() => bBox = !bBox" :checked="bBox"/>
</view>
</view>
<slider :value="penSize" max="20" @change="penSize = $event.detail.value" show-value/>
</view>
</view>
</uni-popup>
<!-- <view class="buttons">
<button @click="onClick('clear')">清空</button>
<button @click="onClick('undo')">撤销</button>
<button @click="onClick('save')">保存</button>
<button @click="bBox = !bBox">bBox{{bBox?'开':'关'}}</button>
<button @click="onClick('openSmooth')">压感{{openSmooth?'开':'关'}}</button>
</view> -->
<!-- <view style="background-color: #2196f3; text-align: center;">
<view style="border: 2px dashed #fff; display: inline-block;">
<image :src="url" v-if="url" style="width: 370rpx;" mode="widthFix"></image>
</view>
</view> -->
<view class="signature-preview" v-if="url">
<image class="signature-preview__image" :src="url" mode="widthFix"></image>
</view>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello',
penColor: 'red',
penSize: 16,
url: '',
show: false,
landscape: false,
openSmooth: true,
bottomHeight: 0,
bBox: true,
isShowPen: false,
customBar: this.CustomBar || 0,
}
},
watch:{
isShowPen(v) {
if(!v) {
this.$refs.popup.close()
} else {
this.$refs.popup.open()
}
}
},
computed: {
// styles() {
// if(this.landscape) {
// return `width: 100vw; height: 100vh`
// }
// return `flex:1`
// },
icon() {
if(this.landscape) {
return `data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c3ZnIHdpZHRoPSI0OCIgaGVpZ2h0PSI0OCIgdmlld0JveD0iMCAwIDQ4IDQ4IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxwYXRoIGQ9Ik00MSAxOUgyOVY3IiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iNCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+PHBhdGggZD0iTTE4IDZINlYxOCIgc3Ryb2tlPSIjMzMzIiBzdHJva2Utd2lkdGg9IjQiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPjxwYXRoIGQ9Ik0zMCA0Mkg0MlYzMCIgc3Ryb2tlPSIjMzMzIiBzdHJva2Utd2lkdGg9IjQiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPjxwYXRoIGQ9Ik03IDI5SDE5VjQxIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iNCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+PHBhdGggZD0iTTQyIDZMMjkgMTkiIHN0cm9rZT0iIzMzMyIgc3Ryb2tlLXdpZHRoPSI0IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48cGF0aCBkPSJNMTkgMjlMNiA0MiIgc3Ryb2tlPSIjMzMzIiBzdHJva2Utd2lkdGg9IjQiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPjwvc3ZnPg==`
}
return `data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c3ZnIHdpZHRoPSI0OCIgaGVpZ2h0PSI0OCIgdmlld0JveD0iMCAwIDQ4IDQ4IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxwYXRoIGQ9Ik02IDZMMTYgMTUuODk5NSIgc3Ryb2tlPSIjMzMzIiBzdHJva2Utd2lkdGg9IjQiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPjxwYXRoIGQ9Ik02IDQxLjg5OTVMMTYgMzIiIHN0cm9rZT0iIzMzMyIgc3Ryb2tlLXdpZHRoPSI0IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48cGF0aCBkPSJNNDIuMDAwMSA0MS44OTk1TDMyLjEwMDYgMzIiIHN0cm9rZT0iIzMzMyIgc3Ryb2tlLXdpZHRoPSI0IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48cGF0aCBkPSJNNDEuODk5NSA2TDMyIDE1Ljg5OTUiIHN0cm9rZT0iIzMzMyIgc3Ryb2tlLXdpZHRoPSI0IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48cGF0aCBkPSJNMzMgNkg0MlYxNSIgc3Ryb2tlPSIjMzMzIiBzdHJva2Utd2lkdGg9IjQiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPjxwYXRoIGQ9Ik00MiAzM1Y0MkgzMyIgc3Ryb2tlPSIjMzMzIiBzdHJva2Utd2lkdGg9IjQiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPjxwYXRoIGQ9Ik0xNSA0Mkg2VjMzIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iNCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+PHBhdGggZD0iTTYgMTVWNkgxNSIgc3Ryb2tlPSIjMzMzIiBzdHJva2Utd2lkdGg9IjQiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPjwvc3ZnPg==`
}
},
methods: {
change() {
this.landscape = !this.landscape;
this.url = ''
},
open() {
// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ,type 属性将失效 ,仅支持 ['top','left','bottom','right','center']
this.$refs.popup.open()
this.show = true
},
onClick(type) {
const {signatureRef} = this.$refs
if (type == 'openSmooth') {
this.openSmooth = !this.openSmooth
return
}
if (type == 'save') {
signatureRef.canvasToTempFilePath({
// destWidth: 300,
// destHeight: 200,
quality: 0.8,
success: (res) => {
uni.getImageInfo({
src: res.tempFilePath,
success(res) {
console.log('Temp res', res)
}
})
this.url = res.tempFilePath
}
})
return
}
if (type == 'save2') {
signatureRef.canvasToMaskPath({
// destWidth: 300,
// destHeight: 200,
success: (res) => {
uni.getImageInfo({
src: res.tempFilePath,
success(res) {
console.log('Mask res', res)
}
})
this.url = res.tempFilePath
}
})
return
}
if (signatureRef)
signatureRef[type]()
}
}
}
</script>
<style lang="scss">
.signature {
/* #ifndef APP-NVUE */
height: calc(100vh - var(--window-top));
/* #endif */
/* #ifdef APP-NVUE */
flex: 1;
/* #endif */
&-area {
/* #ifndef APP-NVUE */
height: calc(100vh - var(--window-top) - 120rpx);
/* #endif */
/* #ifdef APP-NVUE */
flex: 1;
/* #endif */
}
&-text {
position: absolute;
/* #ifndef APP-NVUE */
left: 50%;
top: 50%;
/* #endif */
/* #ifdef APP-NVUE */
left: 375rpx;
top: 375rpx;
/* #endif */
font-size: 60rpx;
color: #ddd;
transform: translate(-50%,-50%);
z-index: -1;
transition: transform 300ms;
}
&-preview {
position: absolute;
bottom: 120rpx;
right: 20rpx;
width: 120px;
background: #000;
box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.05);
&__image {
/* #ifndef APP-NVUE */
width: 100%;
/* #endif */
/* #ifdef APP-NVUE */
flex: 1;
/* #endif */
}
}
&.landscape {
.signature-preview {
bottom: 20rpx;
width: 220px;
}
.signature-text {
transform: translate(-50%,-50%) rotate(90deg);
}
.tools {
z-index: 1;
position: absolute;
left: 10rpx;
bottom: 10rpx;
transform: rotate(90deg) translate(-100%, 0%);
transform-origin: bottom left;
padding: 0 16rpx;
border-radius: 50rpx;
&_item {
padding: 0 16rpx;
}
}
// .popup-wrap {
// box-sizing: border-box;
// height: 750rpx;
// padding-top: 100px;
// padding-bottom: 0;
// transform: rotate(90deg) translate(-100%, 0%);
// transform-origin: bottom left;
// }
}
}
.screen-handle {
position: absolute;
right: 10rpx;
top: 10rpx;
width: 60rpx;
height: 60rpx;
background-color: white;
border-radius: 10rpx;
border: 1rpx solid #ddd;
z-index: 10;
justify-content: center;
align-items: center;
&__image {
/* #ifndef APP-NVUE */
width: 80%;
/* #endif */
/* #ifdef APP-NVUE */
flex: 0.8;
/* #endif */
}
}
.tools {
background-color: #fff;
position: relative;
z-index: 999999;
display: flex;
height: 120rpx;
box-shadow: 0 -10rpx 30rpx rgba(0, 0, 0, 0.05);
/* #ifdef APP-NVUE */
flex-direction: row;
/* #endif */
/* #ifndef APP-NVUE */
padding-bottom: constant(safe-area-inset-bottom);
padding-bottom: env(safe-area-inset-bottom);
/* #endif */
&-item {
flex: 1;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
align-items: center;
justify-content: center;
opacity: 0.6;
transition: opacity 0.1s ease-out;
&.restore{
/* #ifndef APP-NVUE */
transform: scaleX(-1);
/* #endif */
}
&.active {
opacity: 1;
}
&__image {
width: 60rpx;
}
}
}
.popup {
&-wrap {
padding-bottom: 120rpx;
background-color: #fff;
}
&-item {
padding-bottom: 30rpx;
&__head {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
padding: 30rpx;
}
&__title {
font-size: 30rpx;
}
&__more {
flex-direction: row;
&-text {
font-size: 24rpx;
// padding-right 10rpx
color: #999;
}
&-switch {
transform: scale(0.7);
transform-origin: center right;
}
}
}
}
</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(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Signature={})}(this,(function(t){"use strict";function e(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,n)}return i}function i(t){for(var i=1;arguments.length>i;i++){var n=null!=arguments[i]?arguments[i]:{};i%2?e(Object(n),!0).forEach((function(e){s(t,e,n[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):e(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}function n(t){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},n(t)}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t,e){for(var i=0;e.length>i;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}function r(t,e,i){return e&&a(t.prototype,e),i&&a(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t}function s(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function u(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&c(t,e)}function h(t){return h=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},h(t)}function c(t,e){return c=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t},c(t,e)}function l(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function v(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var i,n=h(t);if(e){var o=h(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return l(this,i)}}var f=function(t){var e=n(t);return null!==t&&"object"===e||"function"===e},d={}.toString,p=function(t,e){return d.call(t)==="[object "+e+"]"},y=function(t){return p(t,"String")},g=function(t){return p(t,"Number")},m=function(t){return p(t,"Function")},x=function(){function t(){o(this,t),this.__events=void 0,this.__events={}}return r(t,[{key:"on",value:function(t,e){if(t&&e){var i=this.__events[t]||[];i.push(e),this.__events[t]=i}}},{key:"emit",value:function(t,e){var i=this;if(f(t)&&(t=(e=t)&&e.type),t){var n=this.__events[t];n&&n.length&&n.forEach((function(t){t.call(i,e)}))}}},{key:"off",value:function(t,e){var i=this.__events,n=i[t];if(n&&n.length)if(e)for(var o=0,a=n.length;a>o;o++)n[o]===e&&(n.splice(o,1),o--);else delete i[t]}},{key:"getEvents",value:function(){return this.__events}}]),t}(),w=function(t){u(i,t);var e=v(i);function i(t,n){var a;return o(this,i),(a=e.call(this)).context=void 0,a.canvas=void 0,a.attrs=void 0,a.isCanvasElement=void 0,a.context=t,a.canvas=n.canvas||t.canvas||{width:n.width||0,height:n.height||0},a.attrs=n||{},a.isCanvasElement=!0,a}return r(i,[{key:"width",get:function(){return this.canvas.width},set:function(t){this.canvas.width=t}},{key:"height",get:function(){return this.canvas.height},set:function(t){this.canvas.height=t}},{key:"getContext",value:function(){return this.context}},{key:"getBoundingClientRect",value:function(){var t=this.attrs||{},e=t.top,i=t.right,n=t.width,o=t.height,a=t.left,r=t.bottom;return{top:void 0===e?0:e,width:void 0===n?0:n,right:void 0===i?0:i,height:void 0===o?0:o,bottom:void 0===r?0:r,left:void 0===a?0:a}}},{key:"setAttribute",value:function(t,e){this.attrs[t]=e}},{key:"addEventListener",value:function(t,e){this.on(t,e)}},{key:"removeEventListener",value:function(t,e){this.off(t,e)}},{key:"dispatchEvent",value:function(t,e){this.emit(t,e)}}]),i}(x);var b=function(t,e){return t?function(t){if(!t)return!1;if(1!==t.nodeType||!t.nodeName||"canvas"!==t.nodeName.toLowerCase())return!1;var e=!1;try{t.addEventListener("eventTest",(function(){e=!0})),t.dispatchEvent(new Event("eventTest"))}catch(t){e=!1}return e}(t.canvas)?t.canvas:new w(t,e):null};function k(t,e){try{return t.currentStyle?t.currentStyle[e]:document.defaultView&&document.defaultView.getComputedStyle(t,null).getPropertyValue(e)}catch(t){return{width:300,height:150}[e]}}function _(t,e){var i=e.get("el");if(!i)return t;var n=i.getBoundingClientRect(),o=n.top,a=void 0===o?0:o,r=n.left,s=void 0===r?0:r,u=parseFloat(k(i,"padding-left"))||0,h=parseFloat(k(i,"padding-top"))||0;return{x:t.x-s-u,y:t.y-a-h}}function E(t,e){var i=e.get("landscape");if(!i)return t;if(m(i))return i(t,e);var n=e.get("height");return{x:t.y,y:n-t.x}}var L=function(t,e){var i=t.touches;if(!i||!i.length)return[E(_({x:t.clientX,y:t.clientY},e),e)];i.length||(i=t.changedTouches||[]);for(var n=[],o=0,a=i.length;a>o;o++){var r=i[o],s=r.x,u=r.y,h=r.clientX,c=r.clientY,l=void 0;l=g(s)||g(u)?{x:s,y:u}:_({x:h,y:c},e),n.push(E(l,e))}return n},M=function(t,e){var i=e.x-t.x,n=e.y-t.y;return Math.abs(i)>Math.abs(n)?i>0?"right":"left":n>0?"down":"up"},P=function(t,e){var i=Math.abs(e.x-t.x),n=Math.abs(e.y-t.y);return Math.sqrt(i*i+n*n)},T=function(){function t(e){var i=this,n=e.canvas,a=e.el;o(this,t),this.processEvent=void 0,this.canvas=void 0,this.startTime=0,this.endTime=0,this.startPoints=null,this.startDistance=0,this.center=null,this.pressTimeout=void 0,this.eventType=null,this.direction=null,this.lastMoveTime=0,this.prevMovePoints=null,this.prevMoveTime=0,this.lastMovePoints=null,this.pinch=!1,this._click=function(t){var e=L(t,i.canvas);t.points=e,i.emitEvent("click",t)},this._start=function(t){var e,n,o=L(t,i.canvas);o&&(t.points=o,i.emitEvent("touchstart",t),i.reset(),i.startTime=Date.now(),i.startPoints=o,o.length>1?(i.startDistance=P(o[0],o[1]),i.center={x:(e=o[0]).x+((n=o[1]).x-e.x)/2,y:e.y+(n.y-e.y)/2}):i.pressTimeout=setTimeout((function(){var e="press",n="none";t.direction=n,i.emitStart(e,t),i.emitEvent(e,t),i.eventType=e,i.direction=n}),250))},this._move=function(t){var e=L(t,i.canvas);if(e){t.points=e,i.emitEvent("touchmove",t);var n=i.startPoints;if(n)if(e.length>1){var o=i.startDistance,a=P(e[0],e[1]);t.zoom=a/o,t.center=i.center,i.emitStart("pinch",t),i.emitEvent("pinch",t)}else{var r=e[0].x-n[0].x,s=e[0].y-n[0].y,u=i.direction||M(n[0],e[0]);i.direction=u;var h=i.getEventType(e);t.direction=u,t.deltaX=r,t.deltaY=s,i.emitStart(h,t),i.emitEvent(h,t);var c=i.lastMoveTime,l=Date.now();l-c>0&&(i.prevMoveTime=c,i.prevMovePoints=i.lastMovePoints,i.lastMoveTime=l,i.lastMovePoints=e)}}},this._end=function(t){var e=L(t,i.canvas);t.points=e,i.emitEnd(t),i.emitEvent("touchend",t);var n=i.lastMoveTime;if(100>Date.now()-n){var o=n-(i.prevMoveTime||i.startTime);if(o>0){var a=i.prevMovePoints||i.startPoints,r=i.lastMovePoints;if(!a||!r)return;var s=P(a[0],r[0])/o;s>.3&&(t.velocity=s,t.direction=M(a[0],r[0]),i.emitEvent("swipe",t))}}i.reset();var u=t.touches;u&&u.length>0&&i._start(t)},this._cancel=function(t){i.emitEvent("touchcancel",t),i.reset()},this.canvas=n,this.delegateEvent(a),this.processEvent={}}return r(t,[{key:"delegateEvent",value:function(t){t.addEventListener("click",this._click),t.addEventListener("touchstart",this._start),t.addEventListener("touchmove",this._move),t.addEventListener("touchend",this._end),t.addEventListener("touchcancel",this._cancel)}},{key:"emitEvent",value:function(t,e){this.canvas.emit(t,e)}},{key:"getEventType",value:function(t){var e,i=this.eventType,n=this.startTime,o=this.startPoints;if(i)return i;var a=this.canvas.__events.pan;if(a&&a.length){var r=Date.now();if(!o)return;e=r-n>250&&10>P(o[0],t[0])?"press":"pan"}else e="press";return this.eventType=e,e}},{key:"enable",value:function(t){this.processEvent[t]=!0}},{key:"isProcess",value:function(t){return this.processEvent[t]}},{key:"emitStart",value:function(t,e){this.isProcess(t)||(this.enable(t),this.emitEvent("".concat(t,"start"),e))}},{key:"emitEnd",value:function(t){}},{key:"clearPressTimeout",value:function(){this.pressTimeout&&(clearTimeout(this.pressTimeout),this.pressTimeout=null)}},{key:"reset",value:function(){this.clearPressTimeout(),this.startTime=0,this.startPoints=null,this.startDistance=0,this.direction=null,this.eventType=null,this.pinch=!1,this.prevMoveTime=0,this.prevMovePoints=null,this.lastMoveTime=0,this.lastMovePoints=null}}]),t}(),S=function(t){u(i,t);var e=v(i);function i(t){var n;o(this,i),(n=e.call(this))._attrs={},n._isWindow=void 0,n._attrs=Object.assign({},t),n._isWindow="undefined"!=typeof window,n._initPixelRatio(),n._initCanvas();return["createImage","toDataURL","requestAnimationFrame"].forEach((function(e){n._initAttrs(e,t.canvas||n.get("el"))})),n}return r(i,[{key:"get",value:function(t){return this._attrs[t]}},{key:"set",value:function(t,e){this._attrs[t]=e}},{key:"_initAttrs",value:function(t,e){var i=this;if(!this.get(t)){this.set(t,(function(){return e[t]?e[t].apply(e,arguments):i._isWindow?window[t]?(n=window)[t].apply(n,arguments):"createImage"==t?new Image:null:void 0;var n}))}}},{key:"_initCanvas",value:function(){var t,e,i=this.get("el"),n=this.get("context");if(!i&&!n)throw Error("请指定 id、el 或 context!");t=i?y(i)?(e=i)?document.getElementById(e):null:i:b(n,this._attrs),n&&t&&!t.getContext&&(t.getContext=function(){return n});var o=this.get("width")||function(t){var e=k(t,"width");return"auto"===e&&(e=t.offsetWidth),parseFloat(e)}(t)||t.width,a=this.get("height")||function(t){var e=k(t,"height");return"auto"===e&&(e=t.offsetHeight),parseFloat(e)}(t)||t.height;this.set("canvas",this),this.set("el",t),this.set("context",n||t.getContext("2d")),this.changeSize(o,a);var r=new T({canvas:this,el:t,parent:this.get("parent")});this.set("eventController",r)}},{key:"_initPixelRatio",value:function(){this.get("pixelRatio")||this.set("pixelRatio",window&&window.devicePixelRatio||1)}},{key:"changeSize",value:function(t,e){var i,o=this.get("pixelRatio"),a=this.get("el");(a.style&&(a.style.width=t+"px",a.style.height=e+"px"),(i=a)&&"object"===n(i)&&(1===i.nodeType&&i.nodeName||i.isCanvasElement))&&(a.width=t*o,a.height=e*o,1!==o&&this.get("context").scale(o,o));this.set("width",t),this.set("height",e)}},{key:"destroy",value:function(){if(!this.get("destroyed")){var t=this.get("el");t.width=0,t.height=0,this.clear(),this._attrs={},this.set("destroyed",!0)}}},{key:"clear",value:function(){}},{key:"isDestroyed",value:function(){return this.get("destroyed")}}]),i}(x);var D={penColor:"black",backgroundColor:"",openSmooth:!0,penSize:2,minLineWidth:2,maxLineWidth:6,minSpeed:1.5,maxWidthDiffRate:20,maxHistoryLength:20},O=null,W=function(){function t(e){var i=this;o(this,t),this.canAddHistory=!0,this.points=[],this.historyList=[],this.undoneList=[],this.canvas=void 0,this._isEmpty=!0,this.active=!1,this.getLineWidth=function(t){var e=i.get("options"),n=e.minSpeed,o=e.minLineWidth,a=i.getMaxLineWidth();return Math.min(Math.max(a-(a-o)*t/Math.max(Math.min(n,10),1),o),a)},this.drawTrapezoid=function(t,e,n,o){var a=i.get("context");a.beginPath(),a.moveTo(Number(t.x.toFixed(1)),Number(t.y.toFixed(1))),a.lineTo(Number(e.x.toFixed(1)),Number(e.y.toFixed(1))),a.lineTo(Number(n.x.toFixed(1)),Number(n.y.toFixed(1))),a.lineTo(Number(o.x.toFixed(1)),Number(o.y.toFixed(1))),a.fillStyle=i.get("options").penColor,a.fill(),a.draw&&a.draw(!0)},this.drawNoSmoothLine=function(t,e){e.lastX=t.x+.5*(e.x-t.x),e.lastY=t.y+.5*(e.y-t.y),"number"==typeof t.lastX&&i.drawCurveLine(t.lastX,t.lastY,t.x,t.y,e.lastX,e.lastY,i.getMaxLineWidth())},this.drawCurveLine=function(t,e,n,o,a,r,s){s=Number(s.toFixed(1));var u=i.get("context");u.lineWidth=s,u.beginPath(),u.moveTo(Number(t.toFixed(1)),Number(e.toFixed(1))),u.quadraticCurveTo(Number(n.toFixed(1)),Number(o.toFixed(1)),Number(a.toFixed(1)),Number(r.toFixed(1))),u.stroke(),u.draw&&u.draw(!0)},this.getRadianData=function(t,e,i,n){var o=i-t,a=n-e;if(0===o)return{val:0,pos:-1};if(0===a)return{val:0,pos:1};var r=Math.abs(Math.atan(a/o));return i>t&&e>n||t>i&&n>e?{val:r,pos:1}:{val:r,pos:-1}},this.getRadianPoints=function(t,e,i,n){if(0===t.val)return 1===t.pos?[{x:e,y:i+n},{x:e,y:i-n}]:[{y:i,x:e+n},{y:i,x:e-n}];var o=Math.sin(t.val)*n,a=Math.cos(t.val)*n;return 1===t.pos?[{x:e+o,y:i+a},{x:e-o,y:i-a}]:[{x:e+o,y:i-a},{x:e-o,y:i+a}]},this.drawSmoothLine=function(t,e){var n=e.x-t.x,o=e.y-t.y;if(Math.abs(n)+Math.abs(o)>2?(e.lastX1=t.x+.3*n,e.lastY1=t.y+.3*o,e.lastX2=t.x+.7*n,e.lastY2=t.y+.7*o):(e.lastX1=e.lastX2=t.x+.5*n,e.lastY1=e.lastY2=t.y+.5*o),e.perLineWidth=(t.lineWidth+e.lineWidth)/2,"number"==typeof t.lastX1){if(i.drawCurveLine(t.lastX2,t.lastY2,t.x,t.y,e.lastX1,e.lastY1,e.perLineWidth),t.isFirstPoint)return;if(t.lastX1===t.lastX2&&t.lastY1===t.lastY2)return;var a=i.getRadianData(t.lastX1,t.lastY1,t.lastX2,t.lastY2),r=i.getRadianPoints(a,t.lastX1,t.lastY1,t.perLineWidth/2),s=i.getRadianPoints(a,t.lastX2,t.lastY2,e.perLineWidth/2);i.drawTrapezoid(r[0],s[0],s[1],r[1])}else e.isFirstPoint=!0},this.addHistory=function(){var t=i.get("options").maxHistoryLength;if(t&&i.canAddHistory)if(i.canAddHistory=!1,i.get("createImage")){var e=null;e=i.get("createImage")();var n=i.get("toDataURL")&&i.get("toDataURL")();y(n)?e.src=n:n.then((function(t){e.src=t})),e.onload=function(){var n=O;O=e,i.historyList.push(n),i.historyList=i.historyList.slice(-t)}}else i.historyList.length++},this.drawByImage=function(t){var e=i.get("context"),n=i.get("width"),o=i.get("height");e.clearRect(0,0,n,o);try{t&&e.drawImage(t,0,0,n,o),e.draw&&e.draw(!0)}catch(t){i.historyList.length=0}},this.isEmpty=function(){return i.get("options").maxHistoryLength>0?0===i.historyList.length:i._isEmpty},this.clear=function(){if(!i.get("options").disabled){var t=i.get("context");t.clearRect(0,0,i.get("width"),i.get("height")),t.draw&&t.draw(),i._isEmpty=!0,O=null,i.historyList.length=0}},this.undo=function(){if(!i.get("options").disabled&&(0===i.get("options").maxHistoryLength&&i.clear(),i.get("createImage")&&i.historyList.length)){var t=i.historyList.pop();i.drawByImage(t),i.undoneList.push(O),O=t,i.historyList.length||i.undoneList.length||i.clear()}},this.redo=function(){if(i.undoneList.length&&!i.get("options").disabled){var t=i.undoneList.pop();i.historyList.push(O),i.drawByImage(t),O=t,i._isEmpty=!1}},this.canvas=e,this.canvas.set("pen",D),this.init()}return r(t,[{key:"getOption",value:function(){}},{key:"setOption",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=i({},t),n=e.maxLineWidth;if(n&&t.penSize&&n==D.maxLineWidth){var o=Math.max(n,t.penSize);e.maxLineWidth=o}this.canvas.set("pen",Object.assign({},D,e))}},{key:"get",value:function(t){return this.canvas.get("options"==t?"pen":t)}},{key:"init",value:function(){var t=this;this.get("context").lineCap="round",this.canvas.on("touchstart",(function(e){return t.onDrawStart(e)})),this.canvas.on("touchmove",(function(e){return t.onDrawMove(e)})),this.canvas.on("touchend",(function(e){return t.onDrawEnd(e)}))}},{key:"drawBackground",value:function(){var t=this.get("context"),e=this.get("width"),i=this.get("height"),n=this.get("options"),o=n.backgroundColor,a=n.backgroundImage;o&&(t.fillStyle=o,t.fillRect(0,0,e,i),t.draw&&t.draw(!0)),a&&this.drawByImage(a)}},{key:"getImageData",value:function(t){if(t){var e=this.get("width"),i=this.get("height"),n=this.get("el"),o="CANVAS"===n.nodeName,a=o?e:n.width,r=o?i:n.height;if(o){var s=document.createElement("canvas");s.width=e,s.height=i;var u=s.getContext("2d");u.drawImage(n,0,0,e,i);var h=u.getImageData(0,0,e,i).data;return t(h)}var c,l=this.get("context").getImageData(0,0,a,r);return f(c=l)&&m(c.then)&&m(c.catch)?(l.then((function(e){return t(e.data)})),null):t(l.data)}}},{key:"getMaskedImageData",value:function(t){if(t)return this.getImageData((function(e){for(var i=0;e.length>i;i+=4){0===e[i+3]?(e[i]=0,e[i+1]=0,e[i+2]=0):(e[i]=255,e[i+1]=255,e[i+2]=255)}return t(e)}))}},{key:"getContentBoundingBox",value:function(t){var e=this.get("pixelRatio"),i=this.get("width"),n=this.get("height"),o=this.get("el"),a="CANVAS"===o.nodeName,r=a?i:o.width,s=a?n:o.height;e=a?1:e;return this.getImageData((function(i){for(var n=Math.floor(r),o=n,a=Math.floor(s),u=0,h=0,c=0;i.length>c;c+=4){if(i[c+3]>0){var l=c/4%n,v=Math.floor(c/4/n);o=Math.min(o,l),a=Math.min(a,v),u=Math.max(u,l),h=Math.max(h,v)}}var f={width:(u-o+1)/e,height:(h-a+1)/e,startX:o/e,startY:a/e};return t&&t(f),f}))}},{key:"remove",value:function(){var t=this;this.canvas.off("touchstart",(function(e){return t.onDrawStart(e)})),this.canvas.off("touchmove",(function(e){return t.onDrawMove(e)})),this.canvas.off("touchend",(function(e){return t.onDrawEnd(e)}))}},{key:"disableScroll",value:function(t){t.preventDefault&&this.get("options").disableScroll&&t.preventDefault()}},{key:"onDrawStart",value:function(t){if(!this.get("options").disabled){this.disableScroll(t),this.undoneList.length=0;var e=t.points;if(this.active){this.canAddHistory=!0,this.get("context").strokeStyle=this.get("options").penColor;var i=e[0];this.initPoint(i.x,i.y)}}}},{key:"onDrawMove",value:function(t){if(!this.get("options").disabled&&(this.disableScroll(t),this.active)){var e=t.points[0];this.initPoint(e.x,e.y),this.onDraw()}}},{key:"onDrawEnd",value:function(t){this.active&&!this.get("options").disabled&&(this.addHistory(),this.canAddHistory=!0,this.points=[])}},{key:"onDraw",value:function(){var t=this,e=this.get("context");if(this.points.length>=2){e.lineWidth=this.get("options").penSize||2;var i=this.points.slice(-1)[0],n=this.points.slice(-2,-1)[0],o=function(){t._isEmpty=!1,t.get("options").openSmooth?t.drawSmoothLine(n,i):t.drawNoSmoothLine(n,i)},a=this.get("el").canvas;a&&a.requestAnimationFrame?a.requestAnimationFrame((function(){return o()})):"function"==typeof requestAnimationFrame?requestAnimationFrame((function(){return o()})):o()}}},{key:"getMaxLineWidth",value:function(){var t=this.get("options");return Math.min(t.penSize,t.maxLineWidth)}},{key:"initPoint",value:function(t,e){var i={x:t,y:e,t:Date.now()},n=this.points.slice(-1)[0];if(!n||n.t!==i.t&&(n.x!==t||n.y!==e)){if(this.get("options").openSmooth&&n){var o=this.points.slice(-2,-1)[0];if(i.distance=Math.sqrt(Math.pow(i.x-n.x,2)+Math.pow(i.y-n.y,2)),i.speed=i.distance/(i.t-n.t||.1),i.lineWidth=this.getLineWidth(i.speed),o&&o.lineWidth&&n.lineWidth){var a=(i.lineWidth-n.lineWidth)/n.lineWidth,r=this.get("options").maxWidthDiffRate/100;if(r=r>1?1:.01>r?.01:r,Math.abs(a)>r)i.lineWidth=n.lineWidth*(1+(a>0?r:-r))}}this.points.push(i),this.points=this.points.slice(-3)}}}]),t}(),C=function(){function t(e){o(this,t),this.canvas=void 0,this._ee=void 0,this.pen=void 0;var i=new S(e);i.set("parent",this),this.canvas=i,this._ee=new x,this.pen=new W(i),this.init()}return r(t,[{key:"init",value:function(){this.pen.active=!0}},{key:"destroy",value:function(){this.canvas.destroy()}},{key:"clear",value:function(){this.pen.clear()}},{key:"undo",value:function(){this.pen.undo()}},{key:"redo",value:function(){this.pen.redo()}},{key:"save",value:function(){}},{key:"getContentBoundingBox",value:function(t){return this.pen.getContentBoundingBox(t)}},{key:"getMaskedImageData",value:function(t){return this.pen.getMaskedImageData(t)}},{key:"isEmpty",value:function(){return this.pen.isEmpty()}},{key:"on",value:function(t,e){this._ee.on(t,e)}},{key:"emit",value:function(t,e){this._ee.emit(t,e)}},{key:"off",value:function(t,e){this._ee.off(t,e)}}]),t}();t.Signature=C,t.default=C,Object.defineProperty(t,"__esModule",{value:!0})}));
!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!