Commit 8b1dd38f by cen

fix: 客户签名

1 parent 457787e2
No preview for this file type

2.93 MB | W: | H:

2.93 MB | W: | H:

assets/images/sprite.png
assets/images/sprite.png
assets/images/sprite.png
assets/images/sprite.png
  • 2-up
  • Swipe
  • Onion skin
......@@ -149,12 +149,12 @@ module.exports = {
},
// 0待补单;2提单成功;3提单失败
equityStatus: {
0: {
2: {
text: '已完成',
color: '#2cca74',
background: '#eaf9f1'
},
2: {
0: {
text: '待补录',
color: '#F7A431',
background: '#FFF5E6'
......
......@@ -80,113 +80,6 @@ export default {
},
status() {
return order_mixins.data.equityStatus || {}
},
buttonConfig() {
const config = {
showMoreBtn: false,
showReceptionBtn: false,
primaryButton: null,
secondaryButtons: []
}
const order = this.orderCardDetail
const localUser = this.localUserInfo
// 超管或商户类型1不可操作
if (localUser?.isSuper || localUser?.userType !== 2) {
config.showMoreBtn = order.showInvoiceEntrance || ((order.orderStatus == 3 || order.orderStatus == 5 || (order.orderStatus == 6 && order.refundAmount)) && this.isOrder)
return config
}
// 待上传合同协议且是已支付的订单 (zyPayStatus == 1 且 orderStatus 为 3/4/7)
if (order.zyPayStatus == 1 && (order.orderStatus == 3 || order.orderStatus == 4 || order.orderStatus == 7)) {
config.showMoreBtn = order.showInvoiceEntrance || order.invoicing == 2
config.showReceptionBtn = order.orderStatus != '0'
config.primaryButton = { text: '上传协议', type: 'primary', dataType: 'upload' }
if (order.equityOrderStatus == 0 && order.equityGoodsFlag == 1) {
config.secondaryButtons.push({ text: '去处理', type: 'secondary', dataType: 'handle' })
}
return config
}
// 其他情况 - 订单状态不是4,11,9
if (order.orderStatus != '4' && order.orderStatus != 11 && order.orderStatus != 9) {
config.showMoreBtn = order.showInvoiceEntrance || ((order.orderStatus == 3 || order.orderStatus == 5 || order.orderStatus == 6) && this.isOrder)
config.showReceptionBtn = order.orderStatus != '0'
// 修改协议按钮
if (order.canUpdateZyPayUrl == 1 && order.zyPayStatus == 2) {
config.secondaryButtons.push({ text: '修改协议', type: 'secondary', dataType: 'upload' })
}
if (this.isOrder) {
// 待跟进或待支付状态
if (order.orderStatus == '-1' || order.orderStatus == '0') {
config.primaryButton = {
text: this.btnTxt[order.orderStatus] || (order.orderStatus == '-1' ? '去报价' : '去报价'),
type: 'primary',
dataType: 'price'
}
}
// 非已完成状态
else if (order.orderStatus != 6) {
// 战败状态
if (order.orderStatus == '2') {
config.secondaryButtons.push({ text: '战败', type: 'secondary', dataType: 'defeat' })
config.primaryButton = {
text: this.btnTxt[order.orderStatus] || '去支付',
type: 'primary',
dataType: 'pay'
}
}
// 已支付状态
else if (order.orderStatus == '3') {
if (order.equityGoodsFlag == '1') {
// config.secondaryButtons.push({ text: '客户签名', type: 'secondary', dataType: 'signature' })
}
// 已支付未录单
if (order.equityOrderStatus == '0' && order.equityGoodsFlag == '1') {
config.primaryButton = {
text: this.btnTxt[order.orderStatus] || '去处理',
type: 'primary',
dataType: 'handle'
}
}
}
// 已完成状态
else if (order.orderStatus == '5') {
// 已完成未录单
if (order.equityOrderStatus == '0' && order.equityGoodsFlag == '1') {
config.primaryButton = {
text: this.btnTxt[order.orderStatus] || '去处理',
type: 'primary',
dataType: 'handle'
}
}
}
// 其他状态
else {
config.primaryButton = {
text: this.btnTxt[order.orderStatus] || '处理',
type: 'primary',
dataType: 'default'
}
}
}
// 除待跟进工单,支付方式为门店收款的订单可以在工单详情页面展示撤销按钮
if (!(order.orderStatus == '-1' && order.selectPayType == 2)) {
config.secondaryButtons.push({ text: '撤销', type: 'secondary', dataType: 'revoke' })
}
}
} else {
// 订单状态为4,11,9的情况
config.showMoreBtn = order.showInvoiceEntrance || ((order.orderStatus == 3 || order.orderStatus == 5 || order.orderStatus == 6) && this.isOrder)
}
return config
}
},
data() {
......@@ -279,47 +172,14 @@ export default {
break
}
},
// 撤销工单方法
revokeOrder() {
// 配置弹窗按钮
this.$refs.notice.buttonsList = [
{
text: '取消',
type: 'default',
callback: () => {
this.transmissionOfData = null
this.$refs.notice.close()
}
},
{
text: '撤销',
type: 'primary',
callback: async () => {
// 校验订单是否可撤销(在退款流程中无法撤销)
let refundStep = await uni.$api.equityApi.getOrderRefundStep({ orderCode: this.orderCardDetail.payId })
if (refundStep?.data == 'Y') return _this.showRefundAlert()
this.repeal(this.orderCardDetail.id)
}
}
]
// 打开弹窗
this.$refs.notice.open()
},
//修改客户信息
jumpUpdate() {
this.$emit('jump', 'UpdateOrderInfo', { paramsData: this.orderCardDetail, type: 'UpdateOrderInfo' })
},
//去处理
createorder() {
this.$emit('jump', 'CreateOrder', { paramsData: this.orderCardDetail, type: 'CreateOrder' })
},
//上传协议
uploadContract() {
this.$refs.contractPopupRef.open(this.orderCardDetail)
},
//战败
defeatOrder() {
this.$refs.defeatOrderPopup.open(this.orderCardDetail)
// 补录客户签名
handleSignature() {
this.$emit('jump', 'SignName', { paramsData: this.orderCardDetail, type: 'SignName' })
},
showRefundAlert(type) {
const text = type == 'error' ? '订单已发起退款,禁止标记为错误工单!如需标记错误请联系总部运营。' : '订单已发起退款,禁止撤销!如需撤销请联系总部运营。'
......@@ -330,35 +190,6 @@ export default {
confirmText: '好的'
})
},
repeal(id, revokeReason) {
uni.showLoading({
mask: true
})
let _this = this
let params = {
id
}
if (revokeReason) {
params.revokeReason = revokeReason
}
uni.$api.equityApi.cancelOrderById(params).then(_res_ => {
if (_res_) {
uni.hideLoading()
uni.showToast({
title: '操作成功',
icon: 'success'
})
this.transmissionOfData = null
this.$refs.notice.close()
setTimeout(() => {
this.$emit('refresh')
// _this.getList();
}, 500)
} else {
uni.hideLoading()
}
})
},
confirmSelection() {
if (this.textareaValue) {
uni.$api.equityApi
......@@ -383,88 +214,6 @@ export default {
icon: 'none'
})
}
},
onConfirm(val) {
console.log(val)
let urls = []
if (val && val.contractFiles && Array.isArray(val.contractFiles)) {
urls = val.contractFiles.map(file => file.url).filter(url => url)
}
console.log(urls)
const that = this
if (this.orderCardDetail.zyPayStatus == 2 && this.orderCardDetail.canUpdateZyPayUrl == 1) {
uni.showModal({
title: '修改确认',
content: '本次操作将永久替换原图或协议(仅限1次修改权限),请确认是否更新?',
confirmText: '确定',
confirmColor: '#347BFF',
success(res) {
if (res.confirm) {
uni.showLoading({
mask: true
})
console.log(that.orderCardDetail)
uni.$api.equityApi.updateZyInfo({ id: that.orderCardDetail?.id, zyPayUrl: urls.join(',') }).then(res => {
uni.hideLoading()
uni.showToast({
title: '提交成功',
icon: 'none'
})
setTimeout(() => {
that.$emit('refresh')
// _this.getList();
}, 500)
})
}
}
})
} else {
uni.$api.equityApi
.getQuotationInfoById({
id: this.orderCardDetail?.id
})
.then(res => {
console.log(res, 'res')
let orderInfo = {}
let { default4SStoreInfo } = this.userInfo
orderInfo.check = true
orderInfo.id = res.id
orderInfo.orderId = res.orderId
orderInfo.merchantId4s = default4SStoreInfo?.merchantId
orderInfo.merchantName4s = default4SStoreInfo?.merchantName
orderInfo.referrer = res.referrer
orderInfo.referrerId = res.referrerId
console.log(orderInfo, 'orderInfo')
uni.showLoading({
mask: true
})
uni.$api.equityApi
.updateCustomerInfo({
...orderInfo,
zyPayUrl: urls.join(',')
})
.then(result => {
console.log(result, 'resultresult')
this.$refs.contractPopupRef.close()
uni.hideLoading()
uni.showToast({
title: '提交成功',
icon: 'none'
})
setTimeout(() => {
this.$emit('refresh')
// _this.getList();
}, 500)
})
.catch(err => {
console.log(err)
uni.hideLoading()
})
})
.catch(err => {
uni.hideLoading()
})
}
}
},
get methods() {
......
......@@ -20,6 +20,15 @@
<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>
......@@ -87,8 +96,8 @@ export default {
tabList: [
{ tabName: '全部', num: 0, value: null },
{ tabName: '待补录', num: 0, value: 0 },
{ tabName: '提单失败', num: 0, value: 2 },
{ tabName: '已完成', num: 0, value: 3 }
{ tabName: '提单失败', num: 0, value: 3 },
{ tabName: '已完成', num: 0, value: 2 }
],
tabIndex: 0,
activeIndex: 0,
......@@ -111,7 +120,8 @@ export default {
abnormalPages: 1,
normalPages: 1,
checkListObj: {},
localUserInfo: null
localUserInfo: null,
showTips: true
}
},
mounted() {
......@@ -446,39 +456,6 @@ export default {
}
}
.tips {
display: flex;
align-items: center;
justify-content: center;
font-size: toRpx(28);
width: 100%;
height: toRpx(76);
border-radius: 16px;
opacity: 1;
background: #fef5ea;
margin: toRpx(24) 0;
color: #ff9d0a;
&-text {
margin-top: toRpx(4);
}
.icon-study-tips {
margin-right: toRpx(8);
}
.waitinputorder-btn {
width: toRpx(136);
height: toRpx(50);
border-radius: toRpx(48);
opacity: 1;
background: #ffffff;
color: #4673ff;
font-size: toRpx(24);
font-weight: 500;
text-align: center;
line-height: toRpx(50);
}
}
.waitinputorderPopup .popup-content {
.waitinputorder-tab-container {
width: toRpx(488);
......@@ -619,39 +596,17 @@ export default {
margin-left: toRpx(32);
}
}
}
::v-deep .waitinputorderPopup .uni-popup__wrapper {
border-radius: toRpx(32) toRpx(32) 0 0;
opacity: 1;
width: 100%;
height: 67vh;
background-color: #fff !important;
.popup-top-box {
padding: toRpx(32) toRpx(52);
}
}
::v-deep .abnormalTipsPopup .uni-popup__wrapper {
border-radius: toRpx(32) toRpx(32) 0 0;
opacity: 1;
width: 100%;
height: 51vh;
background-color: #fff !important;
.ul {
height: 100%;
.title {
font-weight: 600;
font-size: toRpx(26);
color: #282829;
margin-bottom: toRpx(8);
}
.li {
font-size: toRpx(26);
color: #282829;
margin-bottom: toRpx(8);
}
.last {
margin-bottom: 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);
}
}
}
......
......@@ -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: {
......
......@@ -49,6 +49,7 @@ import StudyCenterPermissionPopup from '@/components/StudyCenterPermissionPopup.
import EquityManagement from './components/EquityManagement.vue'
import CreateEquity from './components/CreateEquity.vue'
import SignName from './components/SignName.vue'
export default {
mixins: [interceptionMixin],
......@@ -65,7 +66,8 @@ export default {
StudyPopup,
StudyCenterPermissionPopup,
EquityManagement,
CreateEquity
CreateEquity,
SignName
},
data() {
return {
......
## 1.5.7(2025-11-24)
- fix: 修复uniappx 安卓打包报错问题
## 1.5.5(2025-09-18)
- fix: 修复uniappx 微信小程序 横屏时报错
## 1.5.4(2025-09-18)
- fix: 修复uniappx 微信小程序 删除离屏canvas报错
## 1.5.3(2025-08-31)
- feat: 兼容uniappx鸿蒙next
## 1.5.2(2025-04-01)
- fix: 修复`钉钉小程序`无法生成图片的问题
## 1.5.1(2025-03-28)
- fix: uniapp app 缺少,导致报错
## 1.5.0(2025-03-28)
- fix: uniappx 微信小程序的`landscape`报错
## 1.4.9(2025-03-27)
- fix: uniapp 缺少,导致报错
## 1.4.8(2025-03-26)
- fix: uniappx app `change`事件不生效的问题
## 1.4.7(2025-03-25)
- feat: 增加`change`事件
## 1.4.6(2024-07-18)
- chore: 更新文档
## 1.4.5(2024-07-17)
- chore: 删除多余console
## 1.4.4(2024-07-15)
- fix: 修复`钉钉小程序`无法生成图片的问题
## 1.4.3(2024-07-15)
- fix: 修复`钉钉小程序`无法使用的问题
## 1.4.2(2024-07-04)
- fix: 修复`vue2`因类型问题无法使用
## 1.4.1(2024-07-04)
- fix: 修复`uvue`因类型问题无法使用
## 1.4.0(2024-05-21)
- fix: 修复`nvue`因重复`width`和`height`重复导致无法使用
## 1.3.9(2024-04-11)
- feat: 增加`preferToDataURL`porps,是否优先使用`toDataURL`生成图片,在支持`toDataURL`的环境优先使用,会生成base64的图片
## 1.3.8(2024-04-10)
- fix: 修复因兼容抖音导致微信小程序图片不完整
## 1.3.7(2024-04-10)
- fix: 修复uniapp x(web)无法生图的问题
- feat: 支持uniapp x(web on pc)
## 1.3.6(2024-04-09)
- fix: 修复抖音小程序无法生成图片
## 1.3.5(2024-04-01)
- feat: 支持uniapp x ios(app-js)
## 1.3.4(2024-03-11)
- feat: app-vue,app-nvue支持生成图片时传`destWidth`,`destHeight`
## 1.3.3(2024-03-07)
- fix: 修复因小数导致mask无法生成
## 1.3.2(2024-03-06)
- fix: 修复app-vue多重复命名变量导致无法使用
## 1.3.1(2024-03-04)
- fix: 缺少this导致云打包失败
## 1.3.0(2024-02-28)
- feat: 支持uniapp x web
## 1.2.9(2024-02-21)
- fix: 修复微信小程序IOS会断断续续的问题
## 1.2.8(2023-12-21)
- fix: 修复redo函数漏了`,`
## 1.2.7(2023-12-19)
- fix: 修复因非uniapp x默认引入了uts文件,导入无法运行
## 1.2.6(2023-12-18)
- feat: 增加支持uniapp x
## 1.2.5(2023-10-11)
- fix: 修复PC浏览不生效的问题
## 1.2.4(2023-08-28)
- feat: 增加 `disabled`
## 1.2.3(2023-08-26)
- fix: 修复app-nvue 无法生成图片
## 1.2.2(2023-08-24)
- fix: 修复app端获取`boundingBox`尺寸异常
## 1.2.1(2023-08-23)
- fix: 修复因画板尺寸有小数导致`boundingBox`失效
## 1.2.0(2023-08-22)
- fix: vue3 app 无法在第一时间获取到 `getSystemInfoSync` 函数,故在生命周期里获取
## 1.1.9(2023-08-18)
- fix: 排除`backgroundColor`为`transparent`的参数,因为会导致生成空白图片
## 1.1.8(2023-08-16)
- chore: 去掉多余的console.log
## 1.1.7(2023-08-09)
- fix: 修复 支付宝无法生成的问题
## 1.1.6(2023-08-03)
- fix: 多了个 return
## 1.1.5(2023-07-27)
- fix: 修复 微信小程序PC端无法绘制问题
## 1.1.4(2023-07-21)
- fix: 修复 APP 报 `requestAnimationFrame` 的问题
## 1.1.3(2023-07-20)
- fix: 修复 性能较一般的手机 手写会卡顿的问题
## 1.1.2(2023-07-18)
- fix: 修复 非 canvas 2d 微信小程序 无法生成图片
## 1.1.1(2023-07-04)
- feat: 增加 `boundingBox` 属性,只生成有笔画的内容区域,从而缩小图片的尺寸节省空间
## 1.1.0(2023-06-20)
- feat: 增加 `canvasToTempFilePath` 质量参数
## 1.0.9(2023-06-13)
- fix: 修复大屏设备上,画板会被离屏canvas挡住的情况
## 1.0.8(2023-06-12)
- fix: 修复vue2 rendrejs 导入问题
## 1.0.7(2023-06-09)
- fix: 修复vue3 rendrejs 找到不节点问题
## 1.0.6(2023-05-23)
- chore: stylus 改为 scss
## 1.0.5(2023-05-16)
- fix: 修复转临时路径出错
## 1.0.4(2023-04-17)
- chore: 删除多余字符
## 1.0.3(2023-04-15)
- BUG: QQ小程序可以使用,会有报错但不影响使用
## 1.0.2(2023-04-15)
- feat: 支持横屏
- BUG: QQ小程序无法使用,为UNI官方问题,插件所需要的API传this都会报错。
## 1.0.1(2023-04-03)
- fix: 销毁时报错
## 1.0.0(2022-10-27)
- feat: 增加背景色
- feat: 修复 app canvasToTempFilePath 无操作只能执行一次的问题
## 0.8.0(2022-08-22)
- feat: 增加beforeDelay 延时初始化,可用于手写板在弹窗里时
## 0.7.0(2022-08-16)
- fix: 修复缺少 canvasWidth
## 0.6.0(2022-07-16)
- fix: 修复 success is no defined
## 0.5.0(2022-07-09)
- feat: canvasToTempFilePath success 增加返回 isEmpty
- fix: 修复 微信小程序 canvasToTempFilePath 无效问题
## 0.4.0(2022-07-04)
- fix: 生成图片缺少最后一笔
## 0.3.0(2022-05-24)
- chore: 支持多端 H5 小程序 APP APP-NVUE
## 0.2.0(2021-07-09)
- chore: 统一命名规范,无须主动引入组件
- fix: 修复错位问题
## 0.1.0(2021-03-07)
- 首次上传
- 撤消、清空、保存、模拟压感等功能
const uniPlatform = uni.getSystemInfoSync().uniPlatform
export const uniContext = (canvasId, context) => {
let ctx = uni.createCanvasContext(canvasId, context)
if (!ctx.uniDrawImage) {
ctx.uniDrawImage = ctx.drawImage
ctx.drawImage = (image, ...agrs) => {
ctx.uniDrawImage(image.src, ...agrs)
}
}
if (!ctx.getImageData) {
ctx.getImageData = (x, y, width, height) => {
return new Promise((resolve, reject) => {
// #ifdef MP || VUE2
if (context.proxy) context = context.proxy
// #endif
uni.canvasGetImageData({
canvasId,
x,
y,
width:parseInt(width),
height:parseInt(height),
success(res) {
resolve(res)
},
fail(error) {
reject(error)
}
}, context)
})
}
} else {
ctx._getImageData = ctx.getImageData
ctx.getImageData = (x, y, width, height) => {
return new Promise((resolve, reject) => {
ctx._getImageData({
x,
y,
width: parseInt(width) ,
height:parseInt(height),
success(res) {
resolve(res)
},
fail(error) {
reject(error)
}
})
})
}
}
return ctx
}
class Image {
constructor() {
this.currentSrc = null
this.naturalHeight = 0
this.naturalWidth = 0
this.width = 0
this.height = 0
this.tagName = 'IMG'
}
onerror() {}
onload() {}
set src(src) {
this.currentSrc = src
uni.getImageInfo({
src,
success: (res) => {
this.naturalWidth = this.width = res.width
this.naturalHeight = this.height = res.height
this.onload()
},
fail: () => {
this.onerror()
}
})
}
get src() {
return this.currentSrc
}
}
export const createImage = () => {
return new Image()
}
export function useCurrentPage() {
const pages = getCurrentPages();
return pages[pages.length - 1];
}
export const toDataURL = (canvasId, context, options = {}) => {
// #ifdef MP-QQ
// context = context.$scope
// #endif
// #ifdef MP-ALIPAY
context = ''
// #endif
return new Promise((resolve, reject) => {
let {
canvas,
width,
height,
destWidth = 0,
destHeight = 0,
x = 0,
y = 0,
preferToDataURL
} = options
const {
pixelRatio
} = uni.getSystemInfoSync()
// #ifdef MP-ALIPAY
const isDD = typeof dd != 'undefined'
if (!isDD && (!destWidth || !destHeight)) {
destWidth = width * pixelRatio;
destHeight = height * pixelRatio;
width = destWidth;
height = destHeight;
x = x * pixelRatio
y = y * pixelRatio
}
// #endif
const params = {
...options,
canvasId,
id: canvasId,
// #ifdef MP-ALIPAY
x,
y,
width,
height,
destWidth,
destHeight,
// #endif
canvas,
success: (res) => {
// 钉钉小程序 不存在tempFilePath
resolve(res.tempFilePath || res.filePath)
},
fail: (err) => {
reject(err)
}
}
// 抖音小程序canvas 2d不支持canvasToTempFilePath
if (canvas && canvas.toDataURL && preferToDataURL) {
let next = true
const devtools = uni.getSystemInfoSync().platform == 'devtools'
// #ifdef MP-TOUTIAO
next = uni.getSystemInfoSync().platform != 'devtools'
if (!next) {
console.warn('[lime-signature] 抖音开发工具不支持bbox')
}
// #endif
if ((x || y) && next) {
const offCanvas = uni.createOffscreenCanvas({
type: '2d'
});
const ctx = offCanvas.getContext("2d");
const destWidth = Math.floor(width * pixelRatio)
const destHeight = Math.floor(height * pixelRatio)
offCanvas.width = destWidth // canvas.width;
offCanvas.height = destHeight // canvas.height;
// ctx.scale(pixelRatio, pixelRatio)
// ctx.drawImage(canvas, Math.floor(x*pixelRatio), Math.floor(y*pixelRatio), destWidth, destHeight, 0,0, destWidth, destHeight);
// 抖音不能在drawImage使用canvas
const image = canvas.createImage()
image.onload = () => {
ctx.drawImage(image, Math.floor(x * pixelRatio), Math.floor(y * pixelRatio),
destWidth, destHeight, 0, 0, destWidth, destHeight)
const tempFilePath = offCanvas.toDataURL();
resolve(tempFilePath)
if (params.success) {
params.success({
tempFilePath
})
}
}
image.src = canvas.toDataURL()
} else {
const tempFilePath = canvas.toDataURL()
resolve(tempFilePath)
if (params.success) {
params.success({
tempFilePath
})
}
}
} else if (canvas && canvas.toTempFilePath) {
canvas.toTempFilePath(params)
} else {
uni.canvasToTempFilePath(params, context)
}
})
}
\ No newline at end of file
export default {
styles: String,
disableScroll: {
type: Boolean,
default: true
},
type: {
type: String,
default: '2d'
},
// 画笔颜色
penColor: {
type: String,
default: 'black'
},
penSize: {
type: Number,
default: 2
},
// 画板背景颜色
backgroundColor: String,
backgroundImage: String,
// 笔锋
openSmooth: Boolean,
// 画笔最小值
minLineWidth: {
type: Number,
default: 2
},
// 画笔最大值
maxLineWidth: {
type: Number,
default: 6
},
// 画笔达到最小宽度所需最小速度(px/ms),取值范围1.0-10.0,值越小,画笔越容易变细,笔锋效果会比较明显,可以自行调整查看效果,选出自己满意的值。
minSpeed: {
type: Number,
default: 1.5
},
// 相邻两线宽度增(减)量最大百分比,取值范围1-100,为了达到笔锋效果,画笔宽度会随画笔速度而改变,如果相邻两线宽度差太大,过渡效果就会很突兀,使用maxWidthDiffRate限制宽度差,让过渡效果更自然。可以自行调整查看效果,选出自己满意的值。
maxWidthDiffRate: {
type: Number,
default: 20
},
// 限制历史记录数,即最大可撤销数,传入0则关闭历史记录功能
maxHistoryLength: {
type: Number,
default: 20
},
beforeDelay: {
type: Number,
default: 0
},
landscape: {
type: Boolean
},
boundingBox: {
type: Boolean
},
disabled: {
type: Boolean
},
preferToDataURL: Boolean,
pixelRatio: Number
}
\ No newline at end of file
// #ifdef APP-VUE
// import { Signature } from '@signature'
import {
Signature
} from './signature.js'
import {
isTransparent
} from './utils'
export default {
data() {
return {
canvasid: null,
signature: null,
observer: null,
options: {},
saveCount: 0,
}
},
mounted() {
this.$nextTick(this.init)
},
methods: {
checkAndEmitEmptyStatus() {
setTimeout(()=>{
if (this.signature) {
const isEmpty = this.signature.isEmpty()
this.emit({
isEmpty
})
}
},0)
},
init() {
const el = this.$refs.limeSignature || this.$ownerInstance.$el;
this.canvas = document.createElement('canvas')
this.canvas.style = 'width: 100%; height: 100%;'
el.appendChild(this.canvas)
this.signature = new Signature({
el: this.canvas
})
this.signature.pen.setOption(this.options)
const width = this.signature.canvas.get('width')
const height = this.signature.canvas.get('height')
this.canvas?.addEventListener('touchend', this.checkAndEmitEmptyStatus.bind(this))
this.emit({
changeSize: {
width,
height
}
})
},
redo(v) {
if (v && this.signature) {
this.signature.redo()
this.checkAndEmitEmptyStatus()
}
},
undo(v) {
if (v && this.signature) {
this.signature.undo()
this.checkAndEmitEmptyStatus()
}
},
clear(v) {
if (v && this.signature) {
this.signature.clear()
this.checkAndEmitEmptyStatus()
}
},
destroy() {
if (this.canvas) {
this.canvas?.removeEventListener('touchend', this.checkAndEmitEmptyStatus.bind(this))
this.canvas.remove()
}
},
mask(param={}) {
if (this.signature) {
let {destWidth=0, destHeight=0} = JSON.parse(param)
let canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d');
const pixelRatio = this.signature.canvas.get('pixelRatio')
let width = this.signature.canvas.get('width')
let height = this.signature.canvas.get('height')
let context = this.signature.canvas.get('context')
canvas.width = width * pixelRatio
canvas.height = height * pixelRatio
const imageData = context.getImageData(0, 0, width * pixelRatio, height * pixelRatio);
for (let i = 0; i < imageData.data.length; i += 4) {
// 判断当前像素是否透明
const isTransparent = imageData.data[i + 3] === 0;
if (isTransparent) {
// 将透明像素设置为黑色背景
imageData.data[i] = 0;
imageData.data[i + 1] = 0;
imageData.data[i + 2] = 0;
} else {
// 将非透明像素设置为白色内容
imageData.data[i] = 255;
imageData.data[i + 1] = 255;
imageData.data[i + 2] = 255;
}
}
ctx.putImageData(imageData, 0, 0);
if(destWidth&&destHeight){
const _canvas = document.createElement('canvas')
_canvas.width = destWidth
_canvas.height = destHeight
const _context = _canvas.getContext('2d')
_context.drawImage(canvas, 0, 0, destWidth, destHeight)
canvas.remove()
canvas = _canvas
}
this.emit({
save: canvas.toDataURL()
})
canvas.remove()
}
},
save(param) {
let {
fileType = 'png',
quality = 1,
n,
destWidth = 0,
destHeight = 0,
} = JSON.parse(param)
const type = `image/${fileType}`.replace(/jpg/, 'jpeg');
if (n !== this.saveCount) {
this.saveCount = n;
const {
backgroundColor,
backgroundImage,
landscape,
boundingBox
} = this.options
const flag = landscape || backgroundColor || boundingBox||destWidth&&destHeight
const image = this.signature.canvas.get('el').toDataURL(!flag && type, !flag && quality)
if (flag) {
let canvas = document.createElement('canvas')
const pixelRatio = this.signature.canvas.get('pixelRatio')
let width = this.signature.canvas.get('width')
let height = this.signature.canvas.get('height')
let x = 0
let y = 0
const next = () => {
const size = [width, height]
if (landscape) {
size.reverse()
}
canvas.width = size[0] * pixelRatio
canvas.height = size[1] * pixelRatio
const param = [x, y, width, height, 0, 0, width, height].map(item => item * pixelRatio)
const context = canvas.getContext('2d')
if (landscape) {
context.translate(0, width * pixelRatio)
context.rotate(-Math.PI / 2)
}
if (backgroundColor && !isTransparent(backgroundColor)) {
context.fillStyle = backgroundColor
context.fillRect(0, 0, width * pixelRatio, height * pixelRatio)
}
const drawImage = () => {
// param
context.drawImage(this.signature.canvas.get('el'), ...param)
if(destWidth&&destHeight){
const _canvas = document.createElement('canvas')
_canvas.width = destWidth
_canvas.height = destHeight
const _context = _canvas.getContext('2d')
_context.drawImage(canvas, 0, 0, destWidth, destHeight)
canvas.remove()
canvas = _canvas
}
this.emit({
save: canvas.toDataURL(type, quality)
})
canvas.remove()
}
if (backgroundImage) {
const img = new Image();
img.onload = () => {
context.drawImage(img, ...param)
drawImage()
}
img.src = backgroundImage
}
if (!backgroundImage) {
drawImage()
}
}
if (boundingBox) {
const res = this.signature.getContentBoundingBox()
width = res.width
height = res.height
x = res.startX
y = res.startY
next()
} else {
next()
}
} else {
this.emit({
save: image
})
}
}
},
isEmpty(v) {
if (v && this.signature) {
const isEmpty = this.signature.isEmpty()
this.emit({
isEmpty
})
}
},
emit(event) {
this.$ownerInstance.callMethod('onMessage', {
detail: {
data: [{
event
}]
}
})
},
update(v) {
if (v) {
if (this.signature) {
this.options = v
this.signature.pen.setOption(v)
} else {
this.options = v
}
}
}
}
}
// #endif
\ No newline at end of file
// @ts-nocheck
import { LimeSignatureOptions, LimeSignaturePoint, LimeSignatureLine } from '../../index.uts'
let points : LimeSignatureLine = []
let undoStack : LimeSignatureLine[] = [];
let redoStack : LimeSignatureLine[] = [];
let lastX = 0;
let lastY = 0;
// #ifdef APP-ANDROID || APP-IOS
type SignatureUniElement = UniElement
type SignatureCanvasContext = DrawableContext
// #endif
// #ifdef APP-HARMONY
type SignatureUniElement = UniCanvasElement
type SignatureCanvasContext = CanvasRenderingContext2D
// #endif
export class Signature {
el : SignatureUniElement
ctx : SignatureCanvasContext
options : LimeSignatureOptions = {
penColor: 'black',
openSmooth: true,
disableScroll: true,
disabled: false,
penSize: 2,
minLineWidth: 2,
maxLineWidth: 6,
minSpeed: 1.5,
maxWidthDiffRate: 20,
maxHistoryLength: 20
} as LimeSignatureOptions
isEmpty : boolean = true
isDrawing : boolean = false
// historyList : LimeSignaturePoint[][] = []
// id : string
// instance : ComponentPublicInstance
touchstartCallbackWrapper: UniCallbackWrapper|null = null
touchmoveCallbackWrapper: UniCallbackWrapper|null= null
touchendCallbackWrapper: UniCallbackWrapper|null= null
change: ((isEmpty: boolean) => void)|null = null
constructor(el : SignatureUniElement) {
this.el = el
// #ifdef APP-ANDROID || APP-IOS
this.ctx = el.getDrawableContext() as DrawableContext
// #endif
// #ifdef APP-HARMONY
const dpr = uni.getDeviceInfo().devicePixelRatio ?? 1;
el.width = el.offsetWidth * dpr;
el.height = el.offsetHeight * dpr;
this.ctx = el.getContext('2d')
this.ctx.scale(dpr, dpr); // 仅需调用一次,当调用 reset 方法后需要再次 scale
// #endif
this.init()
}
onChange(cb: (isEmpty: boolean) => void){
this.change = cb
}
init() {
this.touchstartCallbackWrapper = this.el.addEventListener('touchstart', this.onTouchStart)
this.touchmoveCallbackWrapper = this.el.addEventListener('touchmove', this.onTouchMove)
this.touchendCallbackWrapper = this.el.addEventListener('touchend', this.onTouchEnd)
}
remove() {
if(this.touchstartCallbackWrapper == null) return
this.el.removeEventListener('touchstart', this.touchstartCallbackWrapper!)
this.el.removeEventListener('touchmove', this.touchmoveCallbackWrapper!)
this.el.removeEventListener('touchend', this.touchendCallbackWrapper!)
}
setOption(options : LimeSignatureOptions) {
this.options = options
}
disableScroll(event : UniTouchEvent) {
event.stopPropagation()
if (this.options.disableScroll) {
{
event.preventDefault()
}
}
}
getTouchLimeSignaturePoint(event : UniTouchEvent) : LimeSignaturePoint {
const rect = this.el.getBoundingClientRect()
const touche = event.touches[0];
const x = touche.clientX
const y = touche.clientY
// const force = touche.force
return {
x: x - rect.left,
y: y - rect.top
} as LimeSignaturePoint
}
onTouchStart: (event : UniTouchEvent) => void = (event : UniTouchEvent) =>{
if (this.options.disabled) {
return
}
this.disableScroll(event)
const { x, y } = this.getTouchLimeSignaturePoint(event)
this.isDrawing = true;
this.isEmpty = false
lastX = x
lastY = y
points.push({ x, y } as LimeSignaturePoint);
}
onTouchMove: (event : UniTouchEvent) => void = (event : UniTouchEvent) =>{
if (this.options.disabled || !this.isDrawing) {
return
}
this.disableScroll(event)
const { x, y } = this.getTouchLimeSignaturePoint(event)
const lineWidth = this.options.penSize
const strokeStyle = this.options.penColor
const point = { x, y } as LimeSignaturePoint
const last = { x: lastX, y: lastY } as LimeSignaturePoint
this.drawLine(point, last, lineWidth, strokeStyle)
lastX = x
lastY = y
points.push({ x, y, c: strokeStyle, w: lineWidth } as LimeSignaturePoint);
}
onTouchEnd: (event : UniTouchEvent) => void = (event : UniTouchEvent) =>{
this.disableScroll(event)
this.isDrawing = false;
undoStack.push(points);
redoStack = [] as LimeSignatureLine[];
points = [] as LimeSignaturePoint[];
this.change?.(this.isEmpty);
}
drawLine(point : LimeSignaturePoint, last : LimeSignaturePoint, lineWidth : number, strokeStyle : string) {
const ctx = this.ctx
ctx.lineWidth = lineWidth
ctx.strokeStyle = strokeStyle
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
ctx.beginPath()
ctx.moveTo(last.x, last.y)
ctx.lineTo(point.x, point.y)
ctx.stroke()
ctx.closePath()
// ctx.update()
this._draw()
}
_clear() {
// #ifdef APP-ANDROID || APP-IOS
this.ctx.reset()
// #endif
// #ifdef APP-HARMONY
this.ctx.clearRect(0,0,100000,100000)
// #endif
}
_draw() {
// #ifdef APP-ANDROID || APP-IOS
this.ctx.update()
// #endif
}
// addHistory() { }
clear() {
// this.ctx.reset()
// this.ctx.update()
this._clear()
this._draw()
this.isEmpty = true
undoStack = [] as LimeSignatureLine[];
redoStack = [] as LimeSignatureLine[];
points = [] as LimeSignaturePoint[];
}
undo() {
if(redoStack.length == this.options.maxHistoryLength && this.options.maxHistoryLength != 0){
return
}
// this.ctx.reset()
this._clear()
if(undoStack.length > 0){
const lastPath : LimeSignatureLine = undoStack.pop()!;
redoStack.push(lastPath);
if(undoStack.length == 0){
this.isEmpty = true
// this.ctx.update()
this._draw()
return
}
for (let l = 0; l < undoStack.length; l++) {
for (let i = 1; i < undoStack[l].length; i++) {
const last = undoStack[l][i - 1]
const point = undoStack[l][i]
this.drawLine(point, last, point.w!, point.c!)
}
}
} else {
// this.ctx.update()
this._draw()
}
}
redo() {
if(redoStack.length < 1) return
const lastPath : LimeSignatureLine = redoStack.pop()!;
undoStack.push(lastPath);
this.isEmpty = false
for (let l = 0; l < undoStack.length; l++) {
for (let i = 1; i < undoStack[l].length; i++) {
const last = undoStack[l][i - 1]
const point = undoStack[l][i]
this.drawLine(point, last, point.w!, point.c!)
}
}
}
// restore() { }
}
\ No newline at end of file
export interface SignaturePadProps {
/**
* 绘图样式(CSS样式字符串)
*/
styles: string
/**
* 画笔颜色
*/
penColor: string
/**
* 画笔粗细(像素)
*/
penSize: number
/**
* 背景颜色
*/
backgroundColor: string
/**
* 是否开启平滑绘制
*/
openSmooth: boolean
/**
* 最小笔触宽度
*/
minLineWidth: number
/**
* 最大笔触宽度
*/
maxLineWidth: number
/**
* 最小绘制速度(像素/秒)
*/
minSpeed: number
/**
* 最大宽度差异率
*/
maxWidthDiffRate: number
/**
* 历史记录最大长度
*/
maxHistoryLength: number
/**
* 是否禁止滚动穿透
*/
disableScroll: boolean
/**
* 组件是否禁用
*/
disabled: boolean
/**
* 是否横屏模式
*/
landscape: boolean
}
\ No newline at end of file
export function compareVersion(v1, v2) {
v1 = v1.split('.')
v2 = v2.split('.')
const len = Math.max(v1.length, v2.length)
while (v1.length < len) {
v1.push('0')
}
while (v2.length < len) {
v2.push('0')
}
for (let i = 0; i < len; i++) {
const num1 = parseInt(v1[i], 10)
const num2 = parseInt(v2[i], 10)
if (num1 > num2) {
return 1
} else if (num1 < num2) {
return -1
}
}
return 0
}
function gte(version) {
let { SDKVersion } = uni.getSystemInfoSync()
// #ifdef MP-ALIPAY
SDKVersion = my.SDKVersion
// #endif
return compareVersion(SDKVersion, version) >= 0;
}
export function canIUseCanvas2d() {
// #ifdef MP-WEIXIN
return gte('2.9.0');
// #endif
// #ifdef MP-ALIPAY
return gte('2.7.0');
// #endif
// #ifdef MP-TOUTIAO
return gte('1.78.0');
// #endif
return false
}
export const wrapEvent = (e) => {
if (!e) return;
if (!e.preventDefault) {
e.preventDefault = function() {};
}
return e;
}
export const requestAnimationFrame = (cb) => {
setTimeout(cb, 30)
}
// #ifdef MP
export const prefix = () => {
// #ifdef MP-TOUTIAO
return tt
// #endif
// #ifdef MP-WEIXIN
return wx
// #endif
// #ifdef MP-BAIDU
return swan
// #endif
// #ifdef MP-ALIPAY
return my
// #endif
// #ifdef MP-QQ
return qq
// #endif
// #ifdef MP-360
return qh
// #endif
}
// #endif
/**
* base64转路径
* @param {Object} base64
*/
export function base64ToPath(base64) {
const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64) || [];
return new Promise((resolve, reject) => {
// #ifdef MP
const p = prefix()
const fs = p.getFileSystemManager()
//自定义文件名
if (!format) {
reject(new Error('ERROR_BASE64SRC_PARSE'))
}
const time = new Date().getTime();
const filePath = `${p.env.USER_DATA_PATH}/${time}.${format}`;
fs.writeFile({
filePath,
data: base64.split(',')[1],
encoding: 'base64',
success() {
resolve(filePath)
},
fail(err) {
reject(err)
}
})
// #endif
// #ifdef APP-PLUS
const bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
bitmap.loadBase64Data(base64, () => {
if (!format) {
reject(new Error('ERROR_BASE64SRC_PARSE'))
}
const time = new Date().getTime();
const filePath = `_doc/uniapp_temp/${time}.${format}`
bitmap.save(filePath, {},
() => {
bitmap.clear()
resolve(filePath)
},
(error) => {
bitmap.clear()
reject(error)
})
}, (error) => {
bitmap.clear()
reject(error)
})
// #endif
})
}
export function sleep(delay) {
return new Promise(resolve => setTimeout(resolve, delay))
}
export function getRect(selector, options = {}) {
const typeDefault = 'boundingClientRect'
const { context, type = typeDefault} = options
return new Promise((resolve, reject) => {
const dom = uni.createSelectorQuery().in(context).select(selector);
const result = (rect) => {
if(rect) {
resolve(rect)
} else {
reject()
}
}
if(type == typeDefault) {
dom[type](result).exec()
} else {
dom[type]({
node: true,
size: true,
rect: true
}, result).exec()
}
});
};
export function isTransparent(color) {
// 判断颜色是否为 transparent
if (color === 'transparent') {
return true;
}
// 判断颜色是否为 rgba 的 a 为 0
if (color.startsWith('rgba')) {
const regex = /\d+(\.\d+)?/g;
const matches = color.match(regex);
if (matches !== null) {
const alpha = parseFloat(matches[3]);
if (alpha === 0) {
return true;
}
}
}
return false;
}
\ No newline at end of file
<template>
<view style="height: 950rpx;">
<l-signature ref="signature" :pen-color="penColor" :pen-size="10" @change="change"></l-signature>
</view>
<image style="width: 750rpx;" :src="url" v-if="url" mode="widthFix"></image>
<!-- <view style="height: 200rpx; overflow: visible;"></view> -->
<view style="padding:16px">
<button type="primary" style="margin-bottom:10px" @click="clear">清空</button>
<button type="primary" style="margin-bottom:10px" @click="undo">撤消</button>
<button type="primary" style="margin-bottom:10px" @click="redo">恢复</button>
<button type="primary" style="margin-bottom:10px" @click="save">生成</button>
</view>
</template>
<script lang="uts">
import type {LimeSignatureToTempFilePathOptions, LimeSignatureToFileSuccess} from '@/uni_modules/lime-signature'
export default {
data() {
return {
penColor: 'red',
url: ''
}
},
methods: {
change(isEmpty:boolean) {
console.log('isEmpty:::', isEmpty)
},
clear() {
const signature = this.$refs['signature'] as LSignatureComponentPublicInstance
signature.clear()
},
undo() {
const signature = this.$refs['signature'] as LSignatureComponentPublicInstance
signature.undo()
},
redo() {
const signature = this.$refs['signature'] as LSignatureComponentPublicInstance
signature.redo()
},
save() {
const signature = this.$refs['signature'] as LSignatureComponentPublicInstance
signature.canvasToTempFilePath({
success: (res : LimeSignatureToFileSuccess) : void => {
console.log('isEmpty', res.isEmpty)
this.url = res.tempFilePath
}
} as LimeSignatureToTempFilePathOptions)
}
},
mounted() {
setTimeout(() => {
this.penColor = 'blue'
}, 2000)
}
}
</script>
<style>
</style>
\ No newline at end of file
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title></title>
<style type="text/css">
html,
body,
canvas {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
overflow-y: hidden;
background-color: transparent;
}
</style>
</head>
<body>
<canvas id="lime-signature"></canvas>
<script type="text/javascript" src="./uni.webview.1.5.3.js"></script>
<script type="text/javascript" src="./signature.js"></script>
<script>
var signature = null;
var timer = null;
var isStart = false;
var options = null
console.log = function(...args) {
postMessage(args);
};
// function stringify(key, value) {
// if (typeof value === 'object' && value !== null) {
// if (cache.indexOf(value) !== -1) {
// return;
// }
// cache.push(value);
// }
// return value;
// };
function checkAndEmitEmptyStatus() {
setTimeout(() => {
if (signature) {
const isEmpty = signature.isEmpty()
emit({
isEmpty
});
}
}, 0)
}
function emit(event, data) {
postMessage({
event,
data: typeof data !== "object" && data !== null ? data : JSON.stringify(data),
});
// cache = [];
}
function postMessage(data) {
uni.postMessage({
data
});
}
function update(v = {}) {
if (signature) {
options = v
signature.pen.setOption(v);
} else {
signature = new Signature.Signature({
el: "lime-signature"
});
canvasEl = signature.canvas.get("el");
options = v
signature.pen.setOption(v)
const width = signature.canvas.get("width");
const height = signature.canvas.get("height");
canvasEl.addEventListener('touchend', checkAndEmitEmptyStatus)
emit({
changeSize: {
width,
height
}
})
}
}
function clear() {
signature.clear()
checkAndEmitEmptyStatus()
}
function undo() {
signature.undo()
checkAndEmitEmptyStatus()
}
function redo() {
signature.redo()
checkAndEmitEmptyStatus()
}
function isEmpty() {
const isEmpty = signature.isEmpty()
emit({
isEmpty
});
}
function isTransparent(color) {
// 判断颜色是否为 transparent
if (color === 'transparent') {
return true;
}
// 判断颜色是否为 rgba 的 a 为 0
if (color.startsWith('rgba')) {
const regex = /\d+(\.\d+)?/g;
const matches = color.match(regex);
if (matches !== null) {
const alpha = parseFloat(matches[3]);
if (alpha === 0) {
return true;
}
}
}
return false;
}
function mask(param) {
clearTimeout(timer);
let {
destWidth = 0, destHeight = 0
} = param
let width = this.signature.canvas.get('width')
let height = this.signature.canvas.get('height')
let canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d');
const pixelRatio = signature.canvas.get('pixelRatio')
canvas.width = width * pixelRatio
canvas.height = height * pixelRatio
this.signature.pen.getMaskedImageData((imageData) => {
ctx.putImageData(imageData, 0, 0);
if (destWidth && destHeight) {
const _canvas = document.createElement('canvas')
_canvas.width = destWidth
_canvas.height = destHeight
const _context = _canvas.getContext('2d')
_context.drawImage(canvas, 0, 0, destWidth, destHeight)
canvas.remove()
canvas = _canvas
}
const path = canvas.toDataURL();
canvas.remove()
if (typeof path == "string") {
const index = Math.ceil(path.length / 8);
for (var i = 0; i < 8; i++) {
if (i == 7) {
emit({
"success": path.substr(i * index, index)
});
} else {
emit({
"file": path.substr(i * index, index)
});
}
}
} else {
console.error("canvas no data");
emit({
"fail": "canvas no data"
});
}
})
}
function save(param) {
// delete param.success;
// delete param.fail;
clearTimeout(timer);
timer = setTimeout(() => {
let {
fileType = 'png', quality = 1, n, destWidth = 0, destHeight = 0
} = param
const type = `image/${fileType}`.replace(/jpg/, 'jpeg');
const {
backgroundColor,
landscape,
boundingBox
} = options
const flag = backgroundColor || landscape || boundingBox || destWidth && destHeight
let path = canvasEl.toDataURL(!flag && type, !flag && quality)
if (flag) {
let canvas = document.createElement('canvas')
const pixelRatio = signature.canvas.get('pixelRatio')
let width = signature.canvas.get('width')
let height = signature.canvas.get('height')
let x = 0
let y = 0
const next = () => {
const size = [width, height]
if (landscape) {
size.reverse()
}
canvas.width = size[0] * pixelRatio
canvas.height = size[1] * pixelRatio
const param = [x, y, width, height, 0, 0, width, height].map(item => item * pixelRatio)
const context = canvas.getContext('2d')
// context.scale(pixelRatio, pixelRatio)
if (landscape) {
context.translate(0, width * pixelRatio)
context.rotate(-Math.PI / 2)
}
if (backgroundColor && !isTransparent(backgroundColor)) {
context.fillStyle = backgroundColor
context.fillRect(0, 0, width * pixelRatio, height * pixelRatio)
}
const drawImage = () => {
}
// param
context.drawImage(signature.canvas.get('el'), ...param)
if (destWidth && destHeight) {
const _canvas = document.createElement('canvas')
_canvas.width = destWidth
_canvas.height = destHeight
const _context = _canvas.getContext('2d')
_context.drawImage(canvas, 0, 0, destWidth, destHeight)
canvas.remove()
canvas = _canvas
}
path = canvas.toDataURL(type, quality)
canvas.remove()
}
if (boundingBox) {
const res = signature.getContentBoundingBox()
width = res.width
height = res.height
x = res.startX
y = res.startY
next()
} else {
next()
}
}
if (typeof path == "string") {
const index = Math.ceil(path.length / 8);
for (var i = 0; i < 8; i++) {
if (i == 7) {
emit({
"success": path.substr(i * index, index)
});
} else {
emit({
"file": path.substr(i * index, index)
});
}
}
} else {
console.error("canvas no data");
emit({
"fail": "canvas no data"
});
}
}, 30);
}
</script>
</body>
</html>
\ No newline at end of file
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e=e||self).uni=n()}(this,(function(){"use strict";try{var e={};Object.defineProperty(e,"passive",{get:function(){!0}}),window.addEventListener("test-passive",null,e)}catch(e){}var n=Object.prototype.hasOwnProperty;function i(e,i){return n.call(e,i)}var t=[];function o(){return window.__dcloud_weex_postMessage||window.__dcloud_weex_}var r=function(e,n){var i={options:{timestamp:+new Date},name:e,arg:n};if(o()){if("postMessage"===e){var r={data:[n]};return window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(r):window.__dcloud_weex_.postMessage(JSON.stringify(r))}var a={type:"WEB_INVOKE_APPSERVICE",args:{data:i,webviewIds:t}};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessageToService(a):window.__dcloud_weex_.postMessageToService(JSON.stringify(a))}if(!window.plus)return window.parent.postMessage({type:"WEB_INVOKE_APPSERVICE",data:i,pageId:""},"*");if(0===t.length){var d=plus.webview.currentWebview();if(!d)throw new Error("plus.webview.currentWebview() is undefined");var s=d.parent(),w="";w=s?s.id:d.id,t.push(w)}if(plus.webview.getWebviewById("__uniapp__service"))plus.webview.postMessageToUniNView({type:"WEB_INVOKE_APPSERVICE",args:{data:i,webviewIds:t}},"__uniapp__service");else{var u=JSON.stringify(i);plus.webview.getLaunchWebview().evalJS('UniPlusBridge.subscribeHandler("'.concat("WEB_INVOKE_APPSERVICE",'",').concat(u,",").concat(JSON.stringify(t),");"))}},a={navigateTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;r("navigateTo",{url:encodeURI(n)})},navigateBack:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.delta;r("navigateBack",{delta:parseInt(n)||1})},switchTab:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;r("switchTab",{url:encodeURI(n)})},reLaunch:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;r("reLaunch",{url:encodeURI(n)})},redirectTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;r("redirectTo",{url:encodeURI(n)})},getEnv:function(e){o()?e({nvue:!0}):window.plus?e({plus:!0}):e({h5:!0})},postMessage:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};r("postMessage",e.data||{})}},d=/uni-app/i.test(navigator.userAgent),s=/Html5Plus/i.test(navigator.userAgent),w=/complete|loaded|interactive/;var u=window.my&&navigator.userAgent.indexOf("AlipayClient")>-1;var g=window.swan&&window.swan.webView&&/swan/i.test(navigator.userAgent);var c=window.qq&&window.qq.miniProgram&&/QQ/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var v=window.tt&&window.tt.miniProgram&&/toutiaomicroapp/i.test(navigator.userAgent);var m=window.wx&&window.wx.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var p=window.qa&&/quickapp/i.test(navigator.userAgent);var f=window.ks&&window.ks.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var l=window.tt&&window.tt.miniProgram&&/Lark|Feishu/i.test(navigator.userAgent);var _=window.jd&&window.jd.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);for(var E,b=function(){window.UniAppJSBridge=!0,document.dispatchEvent(new CustomEvent("UniAppJSBridgeReady",{bubbles:!0,cancelable:!0}))},h=[function(e){if(d||s)return window.__dcloud_weex_postMessage||window.__dcloud_weex_?document.addEventListener("DOMContentLoaded",e):window.plus&&w.test(document.readyState)?setTimeout(e,0):document.addEventListener("plusready",e),a},function(e){if(m)return window.WeixinJSBridge&&window.WeixinJSBridge.invoke?setTimeout(e,0):document.addEventListener("WeixinJSBridgeReady",e),window.wx.miniProgram},function(e){if(c)return window.QQJSBridge&&window.QQJSBridge.invoke?setTimeout(e,0):document.addEventListener("QQJSBridgeReady",e),window.qq.miniProgram},function(e){if(u){document.addEventListener("DOMContentLoaded",e);var n=window.my;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){if(g)return document.addEventListener("DOMContentLoaded",e),window.swan.webView},function(e){if(v)return document.addEventListener("DOMContentLoaded",e),window.tt.miniProgram},function(e){if(p){window.QaJSBridge&&window.QaJSBridge.invoke?setTimeout(e,0):document.addEventListener("QaJSBridgeReady",e);var n=window.qa;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){if(f)return window.WeixinJSBridge&&window.WeixinJSBridge.invoke?setTimeout(e,0):document.addEventListener("WeixinJSBridgeReady",e),window.ks.miniProgram},function(e){if(l)return document.addEventListener("DOMContentLoaded",e),window.tt.miniProgram},function(e){if(_)return window.JDJSBridgeReady&&window.JDJSBridgeReady.invoke?setTimeout(e,0):document.addEventListener("JDJSBridgeReady",e),window.jd.miniProgram},function(e){return document.addEventListener("DOMContentLoaded",e),a}],y=0;y<h.length&&!(E=h[y](b));y++);E||(E={});var B="undefined"!=typeof uni?uni:{};if(!B.navigateTo)for(var S in E)i(E,S)&&(B[S]=E[S]);return B.webView=E,B}));
// @ts-nocheck
export type LimeSignatureToFileSuccess = {
tempFilePath: string
isEmpty: boolean
}
export type LimeSignatureToFileSuccessCallback = (res : LimeSignatureToFileSuccess) => void
export type LimeSignatureToFileFailCallback = (res : TakeSnapshotFail) => void
export type LimeSignatureToFileCompleteCallback = (res : any) => void
export type LimeSignatureToTempFilePathOptions = {
success?: LimeSignatureToFileSuccessCallback
fail?: LimeSignatureToFileFailCallback
complete?: LimeSignatureToFileCompleteCallback
format?: string
}
export type LimeSignatureOptions = {
penColor : string
// backgroundColor : string
openSmooth : boolean
disableScroll : boolean
disabled : boolean
penSize : number
minLineWidth : number
maxLineWidth : number
minSpeed : number
maxWidthDiffRate : number
maxHistoryLength : number
}
export type LimeSignaturePoint = {
x: number
y: number
c?: string
w?: number
}
export type LimeSignatureLine = LimeSignaturePoint[]
\ No newline at end of file
{
"id": "lime-signature",
"displayName": "lime-signature 手写板-签名签字",
"version": "1.5.7",
"description": "手写板签名插件:一款实用的签名插件,支持横屏、背景色、笔画颜色、笔画大小等功能,可生成有内容的区域,减小图片尺寸,节省空间。支持uniapp/uniappx",
"keywords": [
"写字",
"签名",
"电子签名",
"横屏",
"uvue"
],
"repository": "",
"engines": {
"HBuilderX": "^3.5.4",
"uni-app": "^4.74",
"uni-app-x": "^4.75"
},
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "",
"type": "component-vue",
"darkmode": "x",
"i18n": "x",
"widescreen": "x"
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "√",
"aliyun": "√",
"alipay": "x"
},
"client": {
"uni-app": {
"vue": {
"vue2": "√",
"vue3": "√"
},
"web": {
"safari": "√",
"chrome": "√"
},
"app": {
"vue": "√",
"nvue": "-",
"android": {
"extVersion": "",
"minVersion": "21"
},
"ios": "√",
"harmony": "√"
},
"mp": {
"weixin": "√",
"alipay": "√",
"toutiao": "√",
"baidu": "√",
"kuaishou": "√",
"jd": "√",
"harmony": "-",
"qq": "√",
"lark": "√"
},
"quickapp": {
"huawei": "-",
"union": "-"
}
},
"uni-app-x": {
"web": {
"safari": "√",
"chrome": "√"
},
"app": {
"android": {
"extVersion": "",
"minVersion": "21"
},
"ios": "√",
"harmony": "√"
},
"mp": {
"weixin": "√"
}
}
}
}
}
}
\ No newline at end of file
# LimeSignature 写字板
一款用于业务签名等场景的写字板插件,支持横屏、压感模拟、撤销/重做等功能。
## 文档链接
📚 详细文档请访问以下站点:
- [signature 文档 - 站点1](https://limex.qcoon.cn/components/signature.html)
- [signature 文档 - 站点2](https://limeui.netlify.app/components/signature.html)
- [signature 文档 - 站点3](https://limeui.familyzone.top/components/signature.html)
## 安装方法
1. 在 uni-app 插件市场中搜索并导入 `lime-signature`
2. 导入后可能需要重新编译项目。
## 代码演示
### 基本用法
```html
<view style="width: 750rpx ;height: 750rpx;">
<l-signature disableScroll ref="signatureRef" :penColor="penColor" :penSize="penSize" :openSmooth="openSmooth" ></l-signature>
</view>
<view>
<button @click="onClick('clear')">清空</button>
<button @click="onClick('undo')">撤消</button>
<button @click="onClick('save')">保存</button>
<!-- uvue 不支持 openSmooth -->
<button @click="onClick('openSmooth')">压感{{openSmooth?'开':'关'}}</button>
</view>
```
### Uniapp
```js
export default {
data() {
return {
title: 'Hello',
penColor: 'red',
penSize: 5,
url: '',
openSmooth: true
}
},
methods: {
onClick(type) {
if(type == 'openSmooth') {
this.openSmooth = !this.openSmooth
return
}
if (type == 'save') {
this.$refs.signatureRef.canvasToTempFilePath({
success: (res) => {
// 是否为空画板 无签名
console.log(res.isEmpty)
// 生成图片的临时路径
// H5 生成的是base64
this.url = res.tempFilePath
}
})
return
}
if (this.$refs.signatureRef)
this.$refs.signatureRef[type]()
}
}
}
```
### Uniappx
```js
import {LimeSignatureToTempFilePathOptions, LimeSignatureToFileSuccess} from '@/uni_modules/lime-signature'
export default {
data() {
return {
title: 'Hello',
penColor: 'red',
penSize: 5,
url: '',
openSmooth: true
}
},
methods: {
onClick(type: string) {
const signatureRef = this.$refs['signatureRef'] as LSignatureComponentPublicInstance
// APP 不支持
// #ifndef APP
if(type == 'openSmooth') {
this.openSmooth = !this.openSmooth
}
// #endif
if (type == 'save') {
signatureRef.canvasToTempFilePath({
success: (res: LimeSignatureToFileSuccess) => {
// 是否为空画板 无签名
console.log(res.isEmpty)
// 生成图片的临时路径
// H5 生成的是base64
this.url = res.tempFilePath
}
} as LimeSignatureToTempFilePathOptions)
return
}
if(type == 'undo'){
signatureRef.undo()
}
if(type == 'redo'){
signatureRef.redo()
}
if(type == 'clear'){
signatureRef.clear()
}
}
}
}
```
### 横屏
通过设置`landscape`,改变生成图片的方向,达到横屏的作用
```html
<view style="width: 100vw; height: 100vh;">
<l-signature landscape></l-signature>
</view>
<view style="transform: rotate(90deg);">
<button @click="onClick('clear')">清空</button>
<button @click="onClick('undo')">撤消</button>
<button @click="onClick('save')">保存</button>
<button @click="onClick('openSmooth')">压感{{openSmooth?'开':'关'}}</button>
</view>
```
## API 文档
### Props
| 参数 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| `penSize` | 画笔大小 | `number` | `2` |
| `minLineWidth` | 线条最小宽度 | `number` | `2` |
| `maxLineWidth` | 线条最大宽度 | `number` | `6` |
| `penColor` | 画笔颜色 | `string` | `black` |
| `backgroundColor` | 背景颜色(透明背景需留空) | `string` | `` |
| `openSmooth` | 是否模拟压感 | `boolean` | `false` |
| `landscape` | 横屏模式 | `boolean` | `false` |
| `disableScroll` | 禁用滚动 | `boolean` | `true` |
| `disabled` | 禁用写字板 | `boolean` | `false` |
### 事件
| 事件名 | 说明 |
| --- | --- |
| `undo` | 撤销操作 |
| `clear` | 清空画板 |
| `canvasToTempFilePath` | 保存为图片 |
## 支持与赞赏
如果你觉得本插件解决了你的问题,可以考虑支持作者:
| 支付宝赞助 | 微信赞助 |
|------------|------------|
| ![](https://testingcf.jsdelivr.net/gh/liangei/image@1.9/alipay.png) | ![](https://testingcf.jsdelivr.net/gh/liangei/image@1.9/wpay.png) |
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!