dheavjr dheavjr - 6 months ago 123
Node.js Question

Fabric.js create image on Node server after loading canvas from JSON

I've been racking my brain the last couple of days trying to figure this out. In the app I'm writing, a user can upload two images, one that overlays the other. After placing one image on top of the other, they click a button and the canvas is converted to JSON and sent to a node (express) server. The canvas is then recreated by loading the JSON data to the canvas, calling toDataURL with a multiplier of 2 and writing the data to a png file.

router.post('/', function(req, res) {
var canvas = fabric.createCanvasForNode(600, 600);

canvas.loadFromJSON(req.body, function() {
var dataUrl = canvas.toDataURL({
format: 'png',
multiplier: 2
imageSrc = dataUrl.replace(/^data:image\/png;base64,/, "");
fs.writeFile('hello.png', imageSrc, 'base64', function(err) {
console.log('Error: ' + err);

If I don't use a multiplier (i.e. multiplier is 1), a 600x600px image is created, as expected. But when I set the multiplier to 2, to get a higher resolution image, only the top-right quarter of the produced image contains the image created from the canvas.

PNG image that is cutoff

I've found resources online that say this was an issue in previous versions of fabric and I've seen others' workarounds, but nothing seems to fix my issue. Any help, advice or resources would be greatly appreciated!

Maybe I should include an example of how I pass the JSON canvas to the server:

var json = JSON.stringify(canvas);
var http = new XMLHttpRequest();
var url = '/designer';
http.open('POST', url, true);

http.setRequestHeader('Content-type', 'application/json');

http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {


For anyone else's reference, I added these two lines:

var ctx = canvas.getContext('2d');

As well I also changed the dimensions to whatever dimensions I wanted the final image to be (in my case 1200x1200).