Michael J. Calkins
Michael J. Calkins

Reputation: 32655

Reset canvas and reload with JSON in Fabric.js

I'm building something like the kitchensink example except I need to be able to have multiple views.

http://fabricjs.com/kitchensink

Business Card: front and back

As you edit I save the JSON periodically.

When you want to edit the back without reloading the page (because I'm using AngularJS), how do I wipe the current canvas and reload new JSON?

I'm currently loading the JSON, you click change view, I run canvas.clearContext(), and reload the new JSON. This is not working the way I anticipated.

Update

I'm using a directive to manage this canvas. I was making the directive instantiate when JSON was available and when I tried to update it, for whatever reason, would not work.

I removed that and made the directive initiate itself empty and now I just loadJson via service. Yay!

Upvotes: 16

Views: 41134

Answers (2)

Picard
Picard

Reputation: 4102

I had similar problem when running with React, using canvas.clear() wasn't enough - the objects where theoretically removed but there was still something on the scene, that was messing with the new loaded objects, it could be that the events attached to those removed objects... Anyway now I'm using canvas.dispose() for clearing this canvas when reloading the scene and the problems are gone.

You can check the docs.

Upvotes: 6

Kienz
Kienz

Reputation: 3507

Normally canvas.loadFromJSON() clears the whole canvas before loading new objects. Otherwise you can run canvas.clear();.

http://fabricjs.com/docs/fabric.Canvas.html#clear

How do you load your JSON?

Something like this should work:

var json = canvas.toJSON();

canvas.clear();

canvas.loadFromJSON(json, canvas.renderAll.bind(canvas));

After loading JSON it's important to call canvas.renderAll(). In the 2nd parameter of canvas.loadFromJSON(json, callback) you can define a cllback function which is invoked after all objects are loaded/added.

http://fabricjs.com/docs/fabric.Canvas.html#loadFromJSON

Upvotes: 38

Related Questions