JGPcode
JGPcode

Reputation: 167

Draw in react-canvas-draw to image base 64

I would to pass my draw in react-canvas-draw to image in base 64, I have thought of:

var imgData = canvas.toDataURL();

but since it is a library ( React-Canvas-Draw, https://www.npmjs.com/package/react-canvas-draw ) what I am using I do not know very well how to implement it.

The library has the getSaveData method but it only serves to restore the data in their components.

getSaveData() returns the drawing's save-data as a stringified object

I would appreciate any guidance, thank you very much!

CODESANDBOX: https://codesandbox.io/s/jovial-architecture-o4tvz?file=/src/App.js

import "./styles.css";
import { useRef } from 'react'
import CanvasDraw from "react-canvas-draw";

export default function App() {

const canvasRef = useRef(null)

const Draw = canvasRef.current;  



 const handleChange =()=> {

  const data = Draw.getSaveData();
  console.log('Draw', Draw)
  console.log('data', data)
  
 }


  return (
    <div className="App">
      <h1>React-Canvas-Draw</h1>
      <h2>Save draw to image base 64!</h2>

      <CanvasDraw 
       ref={ canvasRef }
       onChange={ handleChange }
      />

    </div>
  );
}

Upvotes: 1

Views: 4266

Answers (1)

jcgil
jcgil

Reputation: 1752

Using function toDataURL() returns Base64 data, that could be saved and be passed as src to img tag (exported drawing), as in this example:

CODESANDBOX: https://codesandbox.io/s/competent-nova-7lbbx?file=/src/App.js:0-959

import { useRef, useState } from "react";
import CanvasDraw from "react-canvas-draw";

export default function App() {
  const canvasRef = useRef(null);
  const [drawing, setDrawing] = useState();

  const handleExport = () => {
    const base64 = canvasRef.current.canvasContainer.childNodes[1].toDataURL();
    setDrawing(base64);
  };

  return (
    <div className="App">
      <h1>React-Canvas-Draw</h1>
      <h2>Save draw to image base 64!</h2>
      <hr />
      <button
        type="button"
        style={{ backgroundColor: "#0A71F1", color: "white" }}
        onClick={handleExport}
      >
        Export Drawing
      </button>
      <br />
      <img src={drawing} alt="exported drawing" />
      <CanvasDraw
        lazyRadius={0}
        brushRadius={2}
        canvasWidth={"339px"}
        canvasHeight={"486px"}
        ref={canvasRef}
      />
    </div>
  );
}

Upvotes: 0

Related Questions