8

Using Fabric.js I am working with a text object that I have named header. When the header area is selected a div is faded in with two input fields that can be used to set text and fill. This is working for me.

What I am attempting to handle next, is when deselecting the header object, I will fade out my div. What is the proper way to handle header.off()?

header.on('selected', function() {

  $('#header-text-edit').fadeIn('fast');

  // watch for header.input changes
  scope.$watch("header.input", function(value) {
    header.text = scope.header.input;
  });

  // watch for header.color changes
  scope.$watch("header.color", function(value) {
    header.fill = scope.header.color;
  });
});
1
  • header.off() would be used to remove event handlers. It doesn't have anything to do with the opposite of an event. on() adds an event handler, off() removes it.
    – Clonkex
    Feb 5, 2021 at 2:21

2 Answers 2

19

You need:

canvas.on('selection:cleared', function() {
  ...
});

Take a look at Events Demo and Events Section in tutorial.

2
  • 3
    It's pretty old but just in case someone stumbles upon it - it is important to note that moving from selection to another selection doesn't fire the 'selection:cleared' event. Oct 18, 2016 at 12:17
  • 2
    To add to what @NimrodShory mentioned, it seems from moving from a selection to another selection doesn't fire object:selected either... why doesn't it do both?..update: it seems selection:updated helps to see whats is happening... Jul 9, 2018 at 23:05
12

For fabricjs 2.0 branch the events for selection on canvas should be as follows:

canvas.on('selection:created', function () {
   //...
});

canvas.on('selection:cleared', function () {
   //...
});

the selected event is for individual objects on canvas

var rect = new fabric.Rect({ width: 100, height: 50, fill: 'green' });
rect.on('selected', function() {
    console.log('selected a rectangle');
});
2
  • If i click on an element and then immediately click on another without clicking elsewhere iam unable to trigger the selection:created for the new element it is only working if the existing elements selection is cleared and next element is clicked, how do i fix this? is there anything else to handle them? Oct 15, 2019 at 13:09
  • you might want to observe selection:updated event as well.
    – Cemal
    Oct 22, 2019 at 21:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.