实现手写签名

思路

首先使用Canvas元素当作画布,在手指触摸画布时开始绘制,根据手指移动轨迹绘制签名。

import { useState, useEffect } from "react"
import Taro from '@tarojs/taro'
import { View, Canvas, Button, Image } from '@tarojs/components'


/**
 * @author: whj
 * @date: 2022/10/18
 * @description: 手动签名示例
 */
export default function Test(params) {
  const [context1, setContext1] = useState(null)
  const [hasDraw, setHasDraw] = useState(false)
  const [src, setSrc] = useState(null)

  useEffect(()=>{
    let context2 = Taro.createCanvasContext('handWriting1')
    context2.setStrokeStyle("#000000")
    context2.setLineWidth(3)
    setContext1(context2)
  },[])
		 
  const touchstart1 = function(e) {
    console.log('touchstart1',e)
    setContext1(str=>{
      str.moveTo(e.touches[0].x, e.touches[0].y)
      return str
    })
    setHasDraw(true) // 要签字了
  }
	  const touchmove1 = function(e) {
	    let x = e.touches[0].x
	    let y = e.touches[0].y
	    context1.setLineWidth(3)
	    context1.lineTo(x, y)
	    context1.stroke()
	    context1.setLineCap('round')
	    context1.draw(true)
	    context1.moveTo(x, y)
	  }
	  const reSign1 = function() { // 重新画
	    context1.draw() // 清空画布
    setHasDraw(false)
    setSrc(null)
	  }
	  const sign1ok = function () {
	    if(!hasDraw){
	      console.log("签字是空白的 没有签字")
	    }else{
	      context1.draw(true, Taro.canvasToTempFilePath({
	        canvasId: 'handWriting1',
	        success(res) {
	          console.log(res.tempFilePath) // 得到了图片下面自己写上传吧
          setSrc(res.tempFilePath)
	        }
	      }))
	    }
	  }
  return(
    <View>
      <View class='sign'>
		 <View class='paper'>
		    <Canvas class='handWriting' disableScroll='true' onTouchStart={(e)=>touchstart1(e)} onTouchMove={(e)=>touchmove1(e)}  canvasId='handWriting1'>
		    </Canvas>
		  </View>
		  <View class='signBtn'>
		    <Button size='' type='primary' onTap={()=>sign1ok()}>完成签字</Button> 
		    <Button size='' type='warn' onTap={()=>reSign1()}>重新签字</Button>
		  </View>
      </View>
      <View class='image' hidden={src?false:true}>
        <Image src={src} ></Image>
      </View>
    </View>
  )
}

版权声明:本文为weixin_46662539原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_46662539/article/details/127390050