FabricJS - Error when loading Canvas from JSON

2019-05-06 19:44发布

问题:

I'm using a custom object extended from fabric.Image in my canvas, as suggested in this answer. When I retrieve the json string from the server, I get odd errors when attempting to load it to the canvas:

var canvas = new fabric.Canvsd();

function loadCanvas(resp) {
  // response object contains a data field
  // that's essentialy a JSON string
  var json = JSON.parse(resp.data);
  canvas.loadFromDatalessJSON(json);
}

I get an odd printout to the console: Cannot call method 'setupState' of undefined (fabric.min.js: 1118). I tried replacing the call with canvas.loadFromJSON(json), and instead got a vague SyntaxError: Unexpected token o error. When I used a regular fabric.Image before the change suggested in the linked thread, this code worked fine. I fear this might be something I'm missing when I extended favric's Image class with aditional data. Thoughts?

回答1:

After some search I saw a similar thread in the fabricjs google group. Turned out I messing up 3 things:

  1. I was missing a fromObject() callback definition in a different location for another custom object I made (I had a couple).
  2. I was using loadFromDatalessJSON() when I should have been using simply loadFromJSON().
  3. I was parsing the json string into an actual JSON using JSON.parse(json) before passing it into the loadFromJSON() function, which expected a json string and handled the parsing internally.

Derp.