react-signature-canvas+hook 实现手写签名并生成图片

  1. yarn add react-signature-canvas @types/react-signature-canvas
  2. 实现手写签名并生成图片,代码如下:
import { Button } from 'antd-mobile';
import React, { useState } from 'react';
import SignatureCanvas from 'react-signature-canvas';
import styles from './index.module.css';

const SignPage = () => {
  const [signImg, setSignImg] = useState('');
  const [signTip, setSignTip] = useState('请签名');

  let sigCanvas: any;
  const clearSign = () => {
    sigCanvas.clear();
  };
  const handleSign = () => {
    setSignImg(sigCanvas.toDataURL('image/png'));
  };

  return (
    <div className={styles.signContainer}>
      <div className={styles.signContent}>
        <SignatureCanvas
          penColor="#000"
          canvasProps={{
            width: 343,
            height: 294,
            className: styles.canvasContainer
          }}
          ref={ref => {
            sigCanvas = ref;
          }}
          onBegin={() => setSignTip('')}
        />
        {signTip && <div className={styles.signTip}>{signTip}</div>}
      </div>
      <div className={styles.buttonContainer}>
        <Button onClick={clearSign} className={styles.clearBtn}>
          清除
        </Button>
        <Button onClick={handleSign} className={styles.signBtn} type="primary">
          签字确认
        </Button>
      </div>
      {signImg && <img alt="" width={56} height={48} src={signImg} />}
    </div>
  );
};

export default SignPage;

项目使用了postcss-px-to-viewport,打包时自动将px单位自动转换成viewport单位。css样式如下:

.signContainer {
  background: #6c5438;
  padding: 22px 16px 15px 16px;
  height: 623px;
  box-sizing: border-box;

  & .signContent {
    position: relative;
    width: 100%;

    & .signTip {
      color: #ccc;
      font-size: 30px;
      text-align: center;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }

  & .canvasContainer {
    border-radius: 10px;
    background: #fff;
  }

  & .buttonContainer {
    display: flex;
    flex-direction: row;
    margin-top: 12px;

    & .clearBtn {
      width: 164px;
      font-size: 18px;
      color: #ac9374;
      border-radius: 5px;
      border-radius: 5px;
      background: none;
      border: 1px solid #ac9374;

      &::before {
        border: none;
      }
    }

    & .signBtn {
      width: 164px;
      margin-left: 15px;
      font-size: 18px;
      background: linear-gradient(135deg, #d8bb9a 0%, #8b6e4c 100%);
      border-radius: 5px;
      color: #fff;
      border: none;

      &::before {
        border: none;
      }
    }
  }
}

你可能感兴趣的:(前端,react,签名,html5,reactjs)