'Can't generate base64 string from react signature canvas in react

I am working on a react project for taking a signature from users. I am using react-signature-canvas to sign users. I want the signature data to be saved in the backend. So how can I change the signature canvas to base64 string? Here is my code.

import React, { useRef, useState } from "react";
import SignaturePad from "react-signature-canvas";
import offer from "./assets/offer.PNG";

const Signature = () => {
  let signPad = useRef({});
  let data = "";
  const clear = () => {
    signPad.current.clear();
  };
  const save = () => {
    data = signPad.current.toDataURL();
  };
  const show = () => {
    signPad.current.fromDataURL(data);
  };
  const imageString = ""; //I want to store it here
  return (
    <div className="p-10 flex flex-col space-y-24 font-serif justify-center items-center">
      <div className="  w-56 mt-10   ">
        <p className="flex justify-start items-start -mx-36">Your Signature</p>
        <div className="flex justify-center items-center">
          <SignaturePad
            canvasProps={{ widtd: 500, height: 200, className: "sigCanvas" }}
            className="border-2 border-black "
            ref={signPad}
          />
        </div>
      </div>
      <div className="flex space-x-4 -mt-24">
        {" "}
        <button onClick={clear}>Clear</button>
        <button onClick={save}>Save</button>
        <button onClick={show}>Show</button>
      </div>
    </div>
  );
};

export default Signature;

Can anyone help me change the signature canvas to base64 string?



Solution 1:[1]

It seems you are already almost correctly set up. Your save function uses the signPad reference that should give you access to the underlying canvas, but for some reason you are calling toDataURL method on a subobject called current of the canvas ref.

Try changing the content of the save function to the following and check the console for base64 string output:

console.log(signPad.toDataURL());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adrian Schweizer