Boden_Units
Boden_Units

Reputation: 133

Saving an image file with node.js from canvas.toDataURL()

Im making an electron app and I want the user to be able to save a screenshot of the current page as an image file. For that I am using html2canvas to create a canvas element of the current body and then convert that canvas to a DataURL

html2canvas(document.body, {
    onrendered: function(canvas) {
        var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");

This works as it is should, but I now want to save this to an image file using Node.js FileSystem

        fs.writeFile("testImg.png", image, 'binary', (err) => {
            if (err) console.log("didnt work", err);
            else console.log("write worked");
        });  

This writes a file called "testImg.png" onto my harddrive, but the file only contains: "[object HTMLImageElement]", size is 25kb

        window.location.href=image;

This opens a dialog for me to save the image file, and actually saves the image too, so my question now is how can I save this image I generate to a file without the user dialog.

Upvotes: 1

Views: 4527

Answers (1)

inukshuk
inukshuk

Reputation: 1457

You can convert the data URL to a buffer using the web file API, e.g., using FileReader.readAsDataURL.

But the far better solution is to take a screenshot using BrowserWindow#capturePage -- this should be much easier than using html2canvas.

Update:

Oops, 'readAsDataURL' would not help you, because you already have a data URL, sorry. You can just decode the URL to a buffer since it is just base64, but you should really look to using 'capturePage' instead, because it is likely the better tool to create screenshots.

Upvotes: 1

Related Questions