Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save an image drawn on the canvas in Electron.js

my code to save image is:

var fs = require('fs');
const dialog = require('electron').remote.dialog;
var canvasBuffer = require('electron-canvas-to-buffer');

dialog.showSaveDialog({title:'Testing a save dialog',defaultPath:'image.jpg'},saveCallback);

function saveCallback(filePath) {
  // as a buffer
  var buffer = canvasBuffer(canvas, 'image/png')
  // write canvas to file
  fs.writeFile('image.png', buffer, function (err) {
    throw err
  })
}

I am not able to save the image drawn on the canvas

the error window shows

img.toPNG is not a function

error.

like image 864
Affsan Abbrar Avatar asked Oct 07 '18 19:10

Affsan Abbrar


Video Answer


1 Answers

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);
    });
}
like image 145
Andre Avatar answered Sep 21 '22 10:09

Andre