Unable to download React Canvas Drawing

5.6k Views Asked by At

I want to download my drawing on the React canvas as a jpeg image file to my desktop, and then pass it to a python file for classification. Can someone specify a code to download the React canvas drawing, or suggest a better way to implement the idea?

clearCanvas({nativeEvent}) {
  var image = this.canvas.toDataURL("image/jpeg");
  nativeEvent.href=image;
  this.ctx.save("C:/Users/PrishitaRay/Pictures/Myimage.jpeg");
  this.ctx = this.canvas.getContext('2d');
  this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  }

This function just clears the react canvas without downloading it first.

2

There are 2 best solutions below

0
On BEST ANSWER

After reading your code, I'm not sure if its related to React. Therefore I'm going to give a non-react solution.

In case you have done some drawing on the canvas like my exampleDrawing function, then just call download function like this.

function exampleDrawing(){
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "#FF0000";
  ctx.fillRect(0,0,150,75);
}

function download(){
  var canvas = document.getElementById("canvas");
  var url = canvas.toDataURL("image/png");
  var link = document.createElement('a');
  link.download = 'filename.png';
  link.href = url;
  link.click();
}

exampleDrawing();
<canvas id="canvas" width="200" height="100">
</canvas>
<button onclick="download();">Download!</button>

What my download function do is to create a URL that contains the canvas's image, generate a link, and then click on it.

And of course you don't have to generate a button and click on it. Just call the download function whenever you want.

0
On

Download Canvas as Image in React (Js only): (React Class Components)

Download As Image Function: chartRef.canvas gives the canvas element, replace it with your Canvas element.

handleChartDownload = (chartRef) => {
const chartCanvas = chartRef.canvas;
if (chartCanvas) {
  const url = chartCanvas.toDataURL("image/png");
  const link = document.createElement("a");
  link.download = "chart.png";
  link.href = url;
  link.click();
}
};

Graph Element: these elements comes under render() function.

Download Button:

<button
        className="btn btn-light"
        onClick={() => this.handleChartDownload(this.chartRef)}
 >Download</button>

Graph: (here Scatter is ChartJsReact component, used for creating graphs)

<Scatter
        ref={(reference) => (this.chartRef = reference)}
        data={this.state.chartData}
        options={this.state.chartOptions}
 />