فهرست منبع

SIG-2026-11-09-V2: 实现竖屏直签 + canvas 2d 重写接口 feat/signature-canvas2d-v2

iwt 2 هفته پیش
والد
کامیت
62657960c2
2فایلهای تغییر یافته به همراه150 افزوده شده و 141 حذف شده
  1. 144 53
      cfc-frontend/components/hand-signature/hand-signature.vue
  2. 6 88
      cfc-frontend/pages/signature/signature.vue

+ 144 - 53
cfc-frontend/components/hand-signature/hand-signature.vue

@@ -14,6 +14,14 @@
   用法:
   用法:
     <hand-signature @confirm="onSign" @clear="onClear" />
     <hand-signature @confirm="onSign" @clear="onClear" />
     onSign(url) { this.signatureDataUrl = url }
     onSign(url) { this.signatureDataUrl = url }
+
+  实现方式(v2 · signature.canvas2d.rewrite):
+    - 改用新版 canvas `type="2d"` + `getContext('2d')` + `fields({node:true})` 接口(参照 RadarChart.vue 标准写法)。
+    - 触摸坐标优先取微信 2d 提供的相对画布坐标 `touches[0].x/y`,不再依赖一次性缓存的 rect
+      (旧实现 rect 只在 mounted 取一次,页面/布局变化后坐标偏移导致「字迹显示不出来」)。
+    - 绘制为同步 `ctx.stroke()`,无需异步 `ctx.draw()`,笔迹实时可见。
+    - 导出用 `uni.canvasToTempFilePath({ canvas: this._canvasNode, ... })` 传 2d canvas 节点。
+    - 预填签名仍走 image 层叠加回显,不画进 2d canvas(hasDrawn 语义沿用:已手绘则盖住预填)。
 -->
 -->
 <template>
 <template>
   <view class="hand-signature">
   <view class="hand-signature">
@@ -26,7 +34,8 @@
     </view>
     </view>
     <view class="signature-canvas-wrap">
     <view class="signature-canvas-wrap">
       <canvas
       <canvas
-        canvas-id="hsCanvas"
+        :id="canvasId"
+        type="2d"
         class="signature-canvas"
         class="signature-canvas"
         :style="'width:100%;height:' + height + 'px;'"
         :style="'width:100%;height:' + height + 'px;'"
         @touchstart.stop.prevent="onTouchStart"
         @touchstart.stop.prevent="onTouchStart"
@@ -85,6 +94,21 @@ export default {
   },
   },
   data: function() {
   data: function() {
     return {
     return {
+      // 2d canvas 节点(导出用,canvasToTempFilePath 传 canvas 而非 canvasId)
+      _canvasNode: null,
+      // canvas id 唯一化(参照 RadarChart:this._uid 保证多实例唯一)
+      canvasId: 'hsCanvas_' + (this._uid || 0),
+      // 实际绘制尺寸与像素比(fields size + dpr)
+      canvasWidth: 0,
+      canvasHeight: 0,
+      dpr: 1,
+      // 画布左上角(fields rect 返回),触摸坐标兜底用
+      _rectLeft: 0,
+      _rectTop: 0,
+      // 组件已销毁标志:mounted 的延迟初始化与重试链需据此停止
+      _destroyed: false,
+      // mounted 延迟初始化定时器引用(beforeDestroy 时清理)
+      _initTimer: null,
       ctx: null,
       ctx: null,
       drawing: false,
       drawing: false,
       lastX: 0,
       lastX: 0,
@@ -93,8 +117,7 @@ export default {
       hasDrawn: false,
       hasDrawn: false,
       agreed: false,
       agreed: false,
       currentDataUrl: this.value || '',
       currentDataUrl: this.value || '',
-      savingLive: false,
-      rect: null
+      savingLive: false
     }
     }
   },
   },
   watch: {
   watch: {
@@ -108,49 +131,121 @@ export default {
   },
   },
   mounted: function() {
   mounted: function() {
     var self = this
     var self = this
-    this.ctx = uni.createCanvasContext('hsCanvas', this)
-    if (!this.ctx) {
-      this.ctx = uni.createCanvasContext('hsCanvas')
+    // 等 DOM 布局完成后初始化 Canvas(带重试,应对微信小程序首次渲染 Canvas 节点延迟;参照 RadarChart)
+    var retryCount = 0
+    var maxRetry = 5
+    function tryInit() {
+      if (self._destroyed) return
+      self.initCanvas(function(success) {
+        if (self._destroyed) return
+        if (!success && retryCount < maxRetry) {
+          retryCount++
+          self._initTimer = setTimeout(tryInit, 60)
+        } else if (!success) {
+          console.log('[HandSignature] 初始化失败,重试 ' + maxRetry + ' 次后放弃', self.canvasId)
+        }
+      })
+    }
+    self._initTimer = setTimeout(tryInit, 100)
+  },
+  beforeDestroy: function() {
+    this._destroyed = true
+    if (this._initTimer) {
+      clearTimeout(this._initTimer)
+      this._initTimer = null
     }
     }
-    // 获取画布实际位置与尺寸(导出/坐标换算用);canvas 可能在 nextTick 后才有布局,失败重试一次
-    this.loadRect()
-    this.$nextTick(function() {
-      if (!self.rect) {
-        setTimeout(function() { self.loadRect() }, 300)
-      }
-    })
   },
   },
   methods: {
   methods: {
-    loadRect: function() {
+    /* ===========================
+     * Canvas 初始化(新版 type=2d 接口)
+     * =========================== */
+    initCanvas: function(cb) {
       var self = this
       var self = this
-      try {
-        // 与全站组件一致:用 .in(this) 将选择器限定到本组件作用域(组件内 canvas 必须带组件实例)
-        var query = uni.createSelectorQuery().in(this)
-        query.select('.signature-canvas').boundingClientRect(function(rect) {
-          if (rect) {
-            self.rect = rect
-            // 有预存签名时清空画布(用空白覆盖),回显交给 image 层
-            if (self.currentDataUrl && !self.hasContent) {
-              var ctx = self.ctx
-              if (ctx) {
-                ctx.setFillStyle('#ffffff')
-                ctx.fillRect(0, 0, rect.width, rect.height)
-                ctx.draw(true)
-              }
+      uni.createSelectorQuery().in(this)
+        .select('#' + this.canvasId)
+        .fields({ node: true, size: true, rect: true })
+        .exec(function(res) {
+          // 兜底:回调内任何异常都必须走 cb(false),否则 mounted 的重试机制永远不触发 → 永久空白且无日志
+          try {
+            if (self._destroyed) return
+            if (!res || !res[0]) {
+              console.log('[HandSignature] 查询失败: 未找到 canvas 节点', self.canvasId)
+              if (cb) cb(false)
+              return
+            }
+            var info = res[0]
+            if (!info.node) {
+              console.log('[HandSignature] node 为空: canvas type=2d 节点获取失败', self.canvasId)
+              if (cb) cb(false)
+              return
+            }
+
+            var canvas = info.node
+            var width = info.width
+            var height = info.height
+            if (!width || !height) {
+              // 兜底:fields size 为 0(flex 塌陷等)时按窗口宽度换算(画布宽 100%)
+              console.log('[HandSignature] 查询尺寸为 0,改用窗口宽度兜底换算', self.canvasId)
+              var winWidth = 375
+              try {
+                var winInfo = uni.getWindowInfo()
+                winWidth = winInfo.windowWidth || 375
+              } catch (e2) {}
+              width = Math.round(winWidth)
+              height = Math.round(self.height || 200)
+              console.log('[HandSignature] 兜底尺寸: ' + width + 'x' + height, self.canvasId)
             }
             }
+
+            var pixelRatio = 2
+            try {
+              var system = uni.getWindowInfo()
+              pixelRatio = system.pixelRatio || 2
+            } catch (e) {
+              console.log('[HandSignature] uni.getWindowInfo() 不可用,使用默认 pixelRatio=2', e)
+            }
+
+            canvas.width = width * pixelRatio
+            canvas.height = height * pixelRatio
+
+            var ctx = canvas.getContext('2d')
+            if (!ctx) {
+              console.log('[HandSignature] canvas.getContext(2d) 返回 null', self.canvasId)
+              if (cb) cb(false)
+              return
+            }
+            ctx.scale(pixelRatio, pixelRatio)
+
+            self.ctx = ctx
+            self._canvasNode = canvas
+            self.canvasWidth = width
+            self.canvasHeight = height
+            self.dpr = pixelRatio
+            self._rectLeft = info.left || 0
+            self._rectTop = info.top || 0
+
+            console.log('[HandSignature] 初始化成功', 'size=' + width + 'x' + height, 'canvasId=' + self.canvasId, 'pixelRatio=' + pixelRatio)
+
+            if (cb) cb(true)
+          } catch (e) {
+            console.warn('[HandSignature] 初始化异常:', e)
+            if (cb) cb(false)
           }
           }
-        }).exec()
-      } catch (e) {}
+        })
     },
     },
+    /* ===========================
+     * 触摸坐标(2d 相对画布,不依赖旧 getPos 缓存 rect)
+     * =========================== */
     getPos: function(e) {
     getPos: function(e) {
-      var touch = e.touches && e.touches[0]
-      var cx = touch ? touch.clientX : (e.clientX || 0)
-      var cy = touch ? touch.clientY : (e.clientY || 0)
-      var rect = this.rect
-      if (rect) {
-        return { x: cx - rect.left, y: cy - rect.top }
+      // 优先:type=2d 时微信触摸事件直接提供相对画布的 x/y(不依赖缓存 rect,坐标不会偏移)
+      var t = e.touches && e.touches[0]
+      var x = (t && t.x) || 0
+      var y = (t && t.y) || 0
+      // 兜底:t.x 未定义(如 H5 旧事件)时用 clientX/clientY - 画布左上角(fields rect 实时返回)
+      if (t && t.x === undefined) {
+        x = (t.clientX || 0) - (this._rectLeft || 0)
+        y = (t.clientY || 0) - (this._rectTop || 0)
       }
       }
-      return { x: cx, y: cy }
+      return { x: x, y: y }
     },
     },
     onTouchStart: function(e) {
     onTouchStart: function(e) {
       var pos = this.getPos(e)
       var pos = this.getPos(e)
@@ -163,15 +258,15 @@ export default {
       var pos = this.getPos(e)
       var pos = this.getPos(e)
       var ctx = this.ctx
       var ctx = this.ctx
       if (!ctx) return
       if (!ctx) return
+      // 同步绘制(2d 接口直接 stroke,无需异步提交重绘)
       ctx.beginPath()
       ctx.beginPath()
       ctx.moveTo(this.lastX, this.lastY)
       ctx.moveTo(this.lastX, this.lastY)
       ctx.lineTo(pos.x, pos.y)
       ctx.lineTo(pos.x, pos.y)
-      ctx.setStrokeStyle(this.strokeColor)
-      ctx.setLineWidth(this.strokeWidth)
-      ctx.setLineCap('round')
-      ctx.setLineJoin('round')
+      ctx.strokeStyle = this.strokeColor
+      ctx.lineWidth = this.strokeWidth
+      ctx.lineCap = 'round'
+      ctx.lineJoin = 'round'
       ctx.stroke()
       ctx.stroke()
-      ctx.draw(false)
       this.lastX = pos.x
       this.lastX = pos.x
       this.lastY = pos.y
       this.lastY = pos.y
       this.hasContent = true
       this.hasContent = true
@@ -198,13 +293,11 @@ export default {
         return
         return
       }
       }
       this.savingLive = true
       this.savingLive = true
-      var rect = this.rect || {}
-      var w = rect.width || 300
-      var h = rect.height || this.height
-      // 注意第二个参数 this:canvas 位于自定义组件内,必须传入组件实例,
-      // 否则微信小程序按页面级 canvas-id 查找不到组件内 canvas,导出必然失败(签名「不好用」的根因之一)。
+      var w = this.canvasWidth || 300
+      var h = this.canvasHeight || this.height
+      // 2d 接口:传 canvas 节点(不再传 canvasId),第二个参数 this 仍指向组件实例
       uni.canvasToTempFilePath({
       uni.canvasToTempFilePath({
-        canvasId: 'hsCanvas',
+        canvas: this._canvasNode,
         x: 0,
         x: 0,
         y: 0,
         y: 0,
         width: w,
         width: w,
@@ -258,13 +351,11 @@ export default {
       this.savingLive = false
       this.savingLive = false
     },
     },
     handleClear: function() {
     handleClear: function() {
-      var self = this
       if (this.savingLive) return
       if (this.savingLive) return
       var ctx = this.ctx
       var ctx = this.ctx
       if (ctx) {
       if (ctx) {
-        var rect = this.rect || {}
-        ctx.clearRect(0, 0, rect.width || 600, rect.height || this.height)
-        ctx.draw(true)
+        // 同步清空(2d 接口无需 ctx.draw())
+        ctx.clearRect(0, 0, this.canvasWidth || 600, this.canvasHeight || this.height)
       }
       }
       this.hasContent = false
       this.hasContent = false
       this.hasDrawn = false
       this.hasDrawn = false
@@ -365,4 +456,4 @@ export default {
 .btn-sign-confirm[disabled] {
 .btn-sign-confirm[disabled] {
   opacity: 0.5;
   opacity: 0.5;
 }
 }
-</style>
+</style>

+ 6 - 88
cfc-frontend/pages/signature/signature.vue

@@ -1,17 +1,12 @@
 <template>
 <template>
   <view class="signature-page">
   <view class="signature-page">
-    <!-- H5 降级提示:不支持 screen.orientation.lock 时提示横置设备(不报错) -->
-    <view v-if="h5DegradeHint" class="rotate-hint">
-      <text class="rotate-hint-text">🔄 请横置设备以获得最佳签名体验</text>
-    </view>
-
     <!-- 顶部标题 -->
     <!-- 顶部标题 -->
     <view class="sig-header">
     <view class="sig-header">
       <text class="sig-title">✍️ 手写签名</text>
       <text class="sig-title">✍️ 手写签名</text>
       <text class="sig-subtitle">请在下方空白区域书写签名,完成后点击「确认」</text>
       <text class="sig-subtitle">请在下方空白区域书写签名,完成后点击「确认」</text>
     </view>
     </view>
 
 
-    <!-- 画布区(横屏铺满,高度按视口短边计算) -->
+    <!-- 画布区(竖屏直签,高度按视口高度减固定栏计算) -->
     <view class="sig-canvas-area">
     <view class="sig-canvas-area">
       <hand-signature
       <hand-signature
         ref="signaturePad"
         ref="signaturePad"
@@ -35,12 +30,11 @@
 
 
 <script>
 <script>
 /*
 /*
- * 独立横屏全屏签名页(WI-1/WI-2)
- * - 复用通用 HandSignature 组件(只读复用,不改组件本身)
+ * 独立竖屏全屏签名页(signature.canvas2d.rewrite,取代旧横屏方案 SIG-2026-11-08-L1)
+ * - 复用通用 HandSignature 组件(v2 已重写为 canvas type=2d,只读复用,不改组件对外契约)
  * - 入参:prefill 经 utils/signature-bus.js 模块级写入(base64 过长不进 URL);
  * - 入参:prefill 经 utils/signature-bus.js 模块级写入(base64 过长不进 URL);
  *         requireAgree / agreeText 走 URL 参数
  *         requireAgree / agreeText 走 URL 参数
- * - 横屏:微信 wx.setPageOrientation({orientation:'landscape'});
- *         H5 screen.orientation.lock('landscape') 包裹 try/catch,不支持时显示「请横置设备」提示
+ * - 竖屏直签:不依赖 wx.setPageOrientation / screen.orientation.lock,任何机型进入即竖屏可写
  * - 回传:onConfirm 经 getOpenerEventChannel().emit('signatureConfirm', dataUrl) 后 navigateBack;
  * - 回传:onConfirm 经 getOpenerEventChannel().emit('signatureConfirm', dataUrl) 后 navigateBack;
  *         返回按钮直接 navigateBack(不回传)
  *         返回按钮直接 navigateBack(不回传)
  */
  */
@@ -57,10 +51,8 @@ export default {
       requireAgree: false,
       requireAgree: false,
       // 同意声明文案
       // 同意声明文案
       agreeText: '我已阅读并确认以上内容真实、准确',
       agreeText: '我已阅读并确认以上内容真实、准确',
-      // 画布高度(px,按横屏视口高度计算)
+      // 画布高度(px,竖屏视口高度减固定栏占用)
       canvasHeight: 200,
       canvasHeight: 200,
-      // H5 无法锁横屏时降级提示
-      h5DegradeHint: false,
       // 防止重复 navigateBack
       // 防止重复 navigateBack
       _backed: false
       _backed: false
     }
     }
@@ -76,11 +68,6 @@ export default {
       if (text) this.agreeText = text
       if (text) this.agreeText = text
     }
     }
     this.canvasHeight = this.computeCanvasHeight()
     this.canvasHeight = this.computeCanvasHeight()
-    this.enterLandscape()
-  },
-  onUnload: function() {
-    // 离开签名页恢复竖屏,不污染其它页面
-    this.restorePortrait()
   },
   },
   methods: {
   methods: {
     // 兼容运行时未解码/已解码两种情况(含特殊字符时兜底不抛错)
     // 兼容运行时未解码/已解码两种情况(含特殊字符时兜底不抛错)
@@ -93,7 +80,7 @@ export default {
       }
       }
       return out
       return out
     },
     },
-    // 横屏视口高度(短边)减去顶部标题/底部操作栏/同意声明占位,得到画布可书写高度
+    // 竖屏视口高度(长边,如 812/844)减去顶部标题/底部操作栏/同意声明占位,得到画布可书写高度
     computeCanvasHeight: function() {
     computeCanvasHeight: function() {
       var win = null
       var win = null
       try {
       try {
@@ -109,57 +96,6 @@ export default {
       var h = parseInt(vh, 10) - reserved
       var h = parseInt(vh, 10) - reserved
       return h > 160 ? h : 160
       return h > 160 ? h : 160
     },
     },
-    // 进入签名页:切横屏(平台分流,条件编译)
-    enterLandscape: function() {
-      // #ifdef MP-WEIXIN
-      try {
-        if (typeof wx !== 'undefined' && typeof wx.setPageOrientation === 'function') {
-          wx.setPageOrientation({
-            orientation: 'landscape'
-          })
-        }
-      } catch (e) {}
-      // #endif
-      // #ifdef H5
-      try {
-        var so = (typeof window !== 'undefined' && window.screen) ? window.screen.orientation : null
-        if (so && typeof so.lock === 'function') {
-          var p = so.lock('landscape')
-          if (p && typeof p.catch === 'function') {
-            var self = this
-            p.catch(function() {
-              // 如非全屏/浏览器不支持 → 降级提示横置设备,不报错
-              self.h5DegradeHint = true
-            })
-          }
-        } else {
-          this.h5DegradeHint = true
-        }
-      } catch (e) {
-        this.h5DegradeHint = true
-      }
-      // #endif
-    },
-    // 离开签名页:恢复竖屏
-    restorePortrait: function() {
-      // #ifdef MP-WEIXIN
-      try {
-        if (typeof wx !== 'undefined' && typeof wx.setPageOrientation === 'function') {
-          wx.setPageOrientation({
-            orientation: 'portrait'
-          })
-        }
-      } catch (e) {}
-      // #endif
-      // #ifdef H5
-      try {
-        var so = (typeof window !== 'undefined' && window.screen) ? window.screen.orientation : null
-        if (so && typeof so.unlock === 'function') {
-          so.unlock()
-        }
-      } catch (e) {}
-      // #endif
-    },
     // HandSignature 确认导出成功(内部「确认签名」按钮已被隐藏,由页面「确认」驱动 handleConfirm 走到这里)
     // HandSignature 确认导出成功(内部「确认签名」按钮已被隐藏,由页面「确认」驱动 handleConfirm 走到这里)
     onConfirm: function(dataUrl) {
     onConfirm: function(dataUrl) {
       var channel = this.getOpenerEventChannel ? this.getOpenerEventChannel() : null
       var channel = this.getOpenerEventChannel ? this.getOpenerEventChannel() : null
@@ -215,24 +151,6 @@ export default {
   overflow: hidden;
   overflow: hidden;
 }
 }
 
 
-/* H5 降级提示(绝对定位,不占布局高度) */
-.rotate-hint {
-  position: absolute;
-  top: 12px;
-  left: 12px;
-  right: 12px;
-  z-index: 20;
-  padding: 10px 16px;
-  background: $brand-primary-soft;
-  border: 2rpx solid $brand-primary;
-  border-radius: 16rpx;
-  text-align: center;
-}
-.rotate-hint-text {
-  font-size: calc(26rpx * var(--font-scale, 1));
-  color: $brand-primary;
-}
-
 /* 顶部标题 */
 /* 顶部标题 */
 .sig-header {
 .sig-header {
   flex-shrink: 0;
   flex-shrink: 0;