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.
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.