Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FabricJS AngularJS Events on Canvas

I'm working on a MEAN Stack Application and i use FabricJS on it. To work easier on it I found https://github.com/michaeljcalkins/angular-fabric and I got most of my stuff working now.

Now I want to do something, if the user clicks on the canvas. Only with FabricJS I have done something like:

$scope.canvas.on('mouse:down', function() {
    alert("mouse down");
});

But now with Angular Fabric I have no access to the canvas directly. That is my controller:

app.controller('FabricCtrl', ['$scope', 'Fabric', 'FabricConstants', 'Keypress', function($scope, Fabric, FabricConstants, Keypress) {
$scope.fabric = {};
$scope.FabricConstants = FabricConstants;

$scope.$on('canvas:created', function() {
    $scope.fabric = new Fabric({
        JSONExportProperties: FabricConstants.JSONExportProperties,
        textDefaults: FabricConstants.textDefaults,
        shapeDefaults: FabricConstants.shapeDefaults,
        json: {}
    });

  $scope.fabric.setCanvasSize(32, 32);
  $scope.fabric.canvasScale = 10;
  $scope.fabric.setZoom();

  Keypress.onSave(function() {
        $scope.updatePage();
    });
});

But i can't do something like:

$scope.fabric.on('mouse:down', function() {
    alert("mouse down");
});

or

$scope.fabric.canvas.on('mouse:down', function() {
    alert("mouse down");
});

If I edit the fabric.js and edit the events directly on canvas, it'll work. But I cant imagine this is the right way, maybe someone has an idea?

like image 886
Chazo Avatar asked Oct 31 '22 03:10

Chazo


1 Answers

Found a solution, so simple. I bound ng-mousedown on my div above the fabric HTML element:

<div class="fabric-container" ng-mousedown="test($event)">
  <canvas fabric="fabric"></canvas>
</div>

And in my Controller I catch the coordinates:

$scope.test = function(event) {
  var x = event.offsetX / $scope.fabric.canvasScale;
  var y = event.offsetY / $scope.fabric.canvasScale;

  // do something with x, y
};
like image 59
Chazo Avatar answered Nov 09 '22 08:11

Chazo