display a canvas as an image

32 Views Asked by At

I have been trying to display and image that is saved in saveData function and then called to be displayed in a handleLoadData function, but when I try to execute I get nothing. If I show in the console the data URL I can see the image is saved.

How can I show the saved image in place?

function Canvas() {
 const [imageUrl, setImageUrl] = useState(null);

 const saveData = (e) => {
    if (canvasRef.current) {
      const canvas = canvasRef.current;
      const ctx = canvas.getContext('2d');
      const dataURL = canvas.toDataURL(); // Save canvas as data URL
      console.log(dataURL)
      localStorage.setItem('canvasImageData', dataURL);
      setSavedImageData(dataURL);
    }
  };

const handleLoadData = () => {
    const loadedImageData = localStorage.getItem('canvasImageData');
    if (loadedImageData) {
      setImageUrl(loadedImageData);
    }
  };

 return (
    <div>
      <h2>Canvas Component</h2>
      <div style={{ width: `400px`, overflow: 'auto' }}>

      {imageUrl ? 
      <img src={imageUrl} alt="Loaded Image" />
      :
        <canvas
          ref={canvasRef}
          width={width}
          height={400}
          style={{ backgroundColor: 'lightgray', width: `${width}px` }}
          onMouseDown={startDrawing}
          onMouseMove={draw}
          onMouseUp={stopDrawing}
          onMouseOut={stopDrawing}
        />
  }
 </div>
      <button onClick={saveData}>Save Drawing</button>
      <button onClick={handleLoadData}>Show Saved Image</button>
    </div>
  );
}
0

There are 0 best solutions below