Skip to main content

According to the handwritten signature component of Canvas...

init-qyfront-end developmentmini-appDingTalkAbout 3 min

Background

Due to business requirements, it is necessary to implement a handwritten signature component on the DingTalk Mini Program. After referring to the implementation of handwritten signatures in WeChat Mini Programs online and considering our own actual needs, we have wrapped it into a popup dialog style, while also referring to the handwritten signature style in DingTalk's approval process. The dependencies used include the mini-ali-ui popup and button components, as well as a local icon.

{
  "component": true,
  "usingComponents": {
    "popup": "mini-ali-ui-rpx/es/popup/index",
    "button": "mini-ali-ui-rpx/es/button/index"
  }
}

Approach

The specific implementation is based on the canvas. The canvas API on the Mini Program side is similar to that of WeChat, so this component should be able to be used on the WeChat side with slight modifications.

Some Issues

  1. The width and height of the canvas must be fixed, so the implementation is based on the actual width obtained multiplied by a fixed ratio for the height. This can be passed directly in the component.
  2. The required parameter dpr is referenced from How to Solve the Blurry Canvas Problemopen in new window.
  3. Perhaps I misunderstood, but the save and restore methods did not achieve the desired effect, so the undo function may need to be implemented in a different way. It has been removed here.
  4. clearRect does not work unless a line of content.beginPath() is added before it. I cannot understand how this issue arises.

Attached: Comparison of clearRect Not Working

clearRect Not Working
clearRect Not Working

Implementation

<popup
  show="{{show}}"
  animation="{{animation}}"
  position="{{position}}"
  onClose="onCancel"
  zIndex="{{zIndex}}"
>
  <view class="box">
    <slot name="toolbar"
      ><view class="toolbar">
        <button type="text" onTap="onCancel">{{cancelButtonText}}</button>
        <text a:if="{{title}}" class="title">{{title}}</text>
        <button type="text" onTap="onConfirm">{{confirmButtonText}}</button>
      </view></slot
    >
    <canvas
      width="{{width*dpr}}"
      height="{{height*dpr}}"
      style="{{'width:'+(width-4)+'px;height:'+(height-4)+'px;'}}"
      class="sign"
      id="sign"
      onTouchMove="move"
      onTouchStart="start"
      onTouchEnd="end"
      onTouchCancel="cancel"
      onLongTap="tap"
      disable-scroll="{{true}}"
      onTap="tap"
    >
    </canvas>
    <image
      class="clear-icon"
      src="/icon/icon_clear.svg"
      onTap="clearClick"
    ></image>
    <!--适应底部-->
    <view style="height: 24rpx"></view>
  </view>
</popup>

This post is translated using ChatGPT, please feedbackopen in new window if any omissions.