Fabricjs and Angularjs Integration

I am trying to create an application that edits simple graphics on the screen, fabricjs is the canvas library I use, and angularjs is the MVW environment I use.

Now the bindings from the DOM to the material work just fine (I press div and the corresponding object on the canvas is selected), but not vice versa. When I click an object on the canvas and it is selected, the corresponding DOM is not updated. I read here that I should use $scope.$apply(); but I'm not sure where to put it.

How to update for $scope state fabric?

You can see the code here , click the Add Rect button to add elements to the canvas, and note that when you click on an element, the name on the right is selected on the canvas, but if you select it directly on the canvas, the button will not be lit.

code: http://plnkr.co/edit/lMogPGjJOXx9HLAdiYqB

+7
angularjs fabricjs
source share
2 answers

FabricJS implements events in its classes, so you can associate arbitrary listeners with them. In your case, you can associate the listener with the "object:selected" event, which will call $scope.$apply() and will be fired when the object is selected on the canvas.

See โ€œEvent Inspectorโ€ and Observable Class Documentation . The Canvas class inherits all of these methods, so you can bind listeners to it. You can even get the selected object, as in the example:

 var canvas = new Fabric.Canvas('canvas_container'); canvas.on("object:selected", function (options, event) { var object = options.target; //This is the object selected // You can do anything you want and then call... $scope.$apply() }); 
+6
source share

Based on the response of Bernardo Dominguez and MeLight's comment, it took me a while to figure it out.

The final solution for the above:

 var canvas; window.onload = function() { canvas = new fabric.Canvas('canvas'); canvas.on("object:selected", function (options, event) { //var object = options.target; //This is the object selected var scope = angular.element(document.getElementById('canvas')).scope(); // You can do anything you want and then call... scope.$apply(); }); }; 

The answer to the AngularJS access area due to the external js function was very useful, along with http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

If you want to see a change in location information when moving, add:

 canvas.on("object:moving", function (options, event) { var scope = angular.element(document.getElementById('canvas')).scope(); scope.$apply(); }); 
+3
source share

All Articles