Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 837
Michael J. Calkins Avatar asked Jan 17 '14 04:01

Michael J. Calkins


People also ask

How to reset canvas in fabric JS?

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

How do I reset my zoom on canvas?

Zoom and Pan basicsSelect Zoom and Pan, and select it again to “reset zoom” and fit all content to the screen. You can also double-tap or double-click on the empty space of the canvas to do that.


2 Answers

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

like image 98
Kienz Avatar answered Oct 22 '22 11:10

Kienz


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.

like image 39
Picard Avatar answered Oct 22 '22 09:10

Picard