React 自定义组件实现手写签名

import * as React from 'react';
import SignaturePad from 'react-signature-canvas';
import { useEffect, useMemo, useRef, useState } from 'react';

const Signature = ({ onBegin }, ref) => {
  const divRef = useRef();

  useEffect(() => {
    ref.current.getSignaturePad()._canvas.width = divRef.current?.clientWidth;
    ref.current.getSignaturePad()._canvas.height =  200;
  }, [divRef.current]);

  // 不添加这个,背景默认是透明的,可以看到图片下层的内容,按需添加
  useEffect(() => {
    let canvas = ref.current._canvas;
    if (canvas.getContext) {
      let ctx = canvas.getContext('2d');
      ctx.fillStyle = '#fff'; //添加颜色
      ctx.fillRect(0, 0, canvas.width, canvas.height);
    }
  }, [ref.current]);

  return (
    
); }; export default React.forwardRef(Signature);

使用:

const [signed, isSigned] = useState(false);

const canvasRef = useRef();

isSigned(true)} />

 其他方法:

  // 确认
  const confirm = (callback) => {
    const canvas = canvasRef.current?.getSignaturePad()._canvas;
    // 图片转为 base64
    const dataurl = canvasRef.current?.toDataURL('image/png').toString();
    //图片上传
    canvas.toBlob((blob) => {
      // 开始上传
  
    }, 'image/png');
  };

  // 清空签名
  const clear = () => {
    canvasRef.current?.clear();
  };

你可能感兴趣的:(react,react.js,手写签名)