Closed czynot closed 4 years ago
I am literally working on the same project right now! Would definitely appreciate
The issue has already been addressed here : https://github.com/embiem/react-canvas-draw/pull/78
But I used something else to achieve this in my program, since I used it in a web application :
function saveImage() {
var sourceCanvas = document.getElementsByTagName("canvas")[1];
var destinationCanvas = document.createElement("canvas");
destinationCanvas.height = sourceCanvas.height;
destinationCanvas.width = sourceCanvas.width;
var destinationContext = destinationCanvas.getContext("2d");
destinationContext.drawImage(sourceCanvas, 0, 0);
destinationContext.globalCompositeOperation = "destination-over";
destinationContext.fillStyle = "black";
destinationContext.fillRect(0, 0, destinationCanvas.width, destinationCanvas.height);
var image = destinationCanvas.toDataURL("image/png");
return image;
}
If you inspect the generated webpage on your browser, there are four canvas elements generated, but the drawing stays on canvas[1]. Since I needed a black background on my drawings, I performed a composite operation to keep the background to black. Two things are worth mentioning here :
toDataURL
on sourceCanvas
if you need a transparent background.This returns the PNG data of the image to the server using a post request. Then you can convert the generated data to PNG in Python this way :
import base64
def saveToPNG(dat):
dat = dat.strip('data:image/png;base64')
dat = dat.strip(',')
dat = base64.b64decode(dat)
with open("image.png", "wb") as f:
f.write(dat)
Do we have a workaround to actually save the image that is generated after drawing to a png or jpg file? I actually wanted to save the image, and send it to the backend and use it with a neural network for Digit Classification. Can this be done?