0

I'm working on an application, in which user creates a series of canvases in their browser (using fabricjs for that purpose). The data are stored in a database, which then are planned to be used on the server side (nodejs) to generate PNG images of the canvases and then put them in a downloadable PDF file (I know I can do all this on the client side but the specificity of the app requires me to do this on the server).

The problem? Whenever I'm trying to create a fabric object in the node, I get the Element is not defined error. Here's a code sample:

function generatePdf(someVeryImportantData) {

    var canvas = new fabric.StaticCanvas(null, { width: 300, height: 500});
    var text = new fabric.IText('Hello world');
                      //  ^ this is where the error occurs
    canvas.add(text); // <-- can't even reach that :-(
}

Node version: 8.11.2

Fabric version: 2.3.6

Tried downgrading node down to version 6, didn't help. It would be great if the solution worked both on client and server side.

qwrtln
  • 281
  • 2
  • 12

3 Answers3

0

You can't do HTML canvas on the server side, it is a HTML5 element.

The only way you can do this is to use a templating library, like jade or the like

Matt Kuhns
  • 1,328
  • 1
  • 13
  • 26
  • Thanks for your reply. Are you sure about this? Such a use case is mentioned in the [official docs](http://fabricjs.com/fabric-intro-part-4#node). There are also [issues on github](https://github.com/fabricjs/fabric.js/issues/4586) referencing this. Still, couldn't do anything studying those. – qwrtln Sep 12 '18 at 20:18
  • 1
    That example is using fabric.createCanvasForNode, then streaming it to file, which can then be served. That looks like it might work. You are using fabric.StaticCanvas, which looks like a front end function that is trying to grab an element from the DOM. In nodejs, there is no DOM. – Matt Kuhns Sep 12 '18 at 20:24
  • Well, I've read some blog posts (for instance [here](http://promincproductions.com/blog/installing-fabricjs-for-nodejs-on-linux/)) about projects in which people actually do pull it off but due to proprietary nature of their code they're not really willing to disclose it. Thanks for your help. – qwrtln Sep 12 '18 at 20:33
0

It seems IText has an external dependency: fonts. Those are included by default in the web browser, not so much in nodejs, where they should be supplied explicitly. Using simple objects like geometric shapes works fine.

qwrtln
  • 281
  • 2
  • 12
0

You need to import fabric js this way

const fabric = require("fabric").fabric;