How can I fire custom events on canvas in Fabric J

2019-04-15 03:49发布

问题:

How can i fire custom events on canvas in fabric js?

I want to register javaScript events on canvas in fabric js.

回答1:

If you want to extend fabricjs event system with your custom events, that is pretty simple:

var canvas = new fabric.Canvas('c');
// listen for any event like fabricjs do
canvas.on('custom:event', function(event) {
  // you will have your data here in `event` object 
});
// fire any event with any payload you want
canvas.fire('custom:event', { any: 'payload' });

I prefer this way as you do not use any other libs and still have the same syntax in all the cases (native and custom events).

UPDATE! Do not forget that you should define listener BEFORE firing an event! Check this fiddle with a working example.