Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabric.js going directly from JSON to PNG

I need to create PNG thumbnails of saved stringified JSON from fabric.js

I have a database I am saving the JSON data from the canvas to, but I need to create a PNG thumbnail gallery from this saved JSON data.

Rather than creating a bunch of canvases on the page and doing something like this.

canvas.loadFromJSON(JSONDATA); 
thumbImage = canvas.toDataURL('png');
$(this).attr('src', thumbImage);

I need to just directly create PNGs from the JSON Data. Is this possible, if so how do I do it?

like image 705
Anthony Allard Avatar asked Oct 15 '15 15:10

Anthony Allard


2 Answers

you have an another alternative way is to creat a generation canvas and give it a none displaying, create a hidden canvas to generate your png's, like that you can have generated images from a hidden content canvas.

<canvas id='c' width='150' heigh='150' style='display: none;'><canvas>

<script>
    var canvas = new fabric.Canvas('c');
    canvas.loadFromJSON(json);
    canvas.toDataURL('png');
</script>
like image 171
Day Walker Avatar answered Oct 19 '22 08:10

Day Walker


The JSON data is a set of instructions for FabricJS to use to create a canvas. A canvas can then be converted to an image.

For that reason, yes, you will need to create the canvas and then create the image.

An alternative method would be to create a server running NodeJS, which can run FabricJS. Ultimately you'd perform the same task there - create a canvas and then generate the image. But the benefit here is that being that it's a server process it would save the files directly to the server and thus this task could be automated.

But setting up the server and writing the script to perform this task may take more effort than your task requires - depends on how often you'll need to do this.

This post discusses how to install NodeJS and FabricJS. That'll get the server up and running, but you then need to also write the server script.

like image 24
PromInc Avatar answered Oct 19 '22 07:10

PromInc