How to save an image drawn on the canvas in Electron.js
I assume that your canvas
is correct and already drawn. So you don't need canvas-to-buffer.
Try this approach. (I used jpg, but png works as well)
function saveCallback(filePath) {
// Get the DataUrl from the Canvas
const url = canvas.toDataURL('image/jpg', 0.8);
// remove Base64 stuff from the Image
const base64Data = url.replace(/^data:image\/png;base64,/, "");
fs.writeFile(filePath, base64Data, 'base64', function (err) {
console.log(err);
});
}
Don't use toDataURL()
. There is toBlob()
which is designed for this purpose. Something like this (totally untested):
async function saveCallback(filePath) {
const blob = await new Promise(
(resolve) => canvas.toBlob(blob => resolve(blob), "image/jpg", 0.8)
);
const buffer = new Buffer(await blob.arrayBuffer());
await new Promise(
(resolve, reject) => fs.writeFile(
filePath,
buffer,
"binary",
(err) => {
if (err === null) {
resolve();
} else {
reject(err);
}
}
)
);
}