Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger fabric.js "object:modified" event programmatically?

I want to fire the 'object:modified' event programmatically. I already tried with "fire" and "trigger" methods.

var canvas = new fabric.Canvas('c');

canvas.on("object:modified", function (e) {
    alert("object modified");
});

var text = new fabric.Text('Text', {
  fontFamily: 'Hoefler Text',
  left: 10,
  top: 10
});

canvas.add(text);

$('.fillText').click(function(){
  text.setFill($(this).data('color'));
  canvas.renderAll();

  text.trigger('modified');
});

$('#moveText').click(function(){
  text.setLeft(50);
  text.setTop(50);
  text.setCoords();
  canvas.renderAll();

  text.trigger('modified');
});

https://jsfiddle.net/gb4u85q4/

like image 583
Ogreucha Avatar asked Jun 06 '16 10:06

Ogreucha


2 Answers

You can trigger events using canvas.trigger('<eventname>', options);. fire is deprecated, so you should probably avoid using that.

Since you wanted to trigger object:modified, you can do that in the following way, while passing which object was modified:

canvas.trigger('object:modified', {target: text});

I updated your JSFiddle with the solution added to it. :) (note that I changed the alert to an console.log because I find alerts annoying, you can view the output of console.log in the developer tools, which can be opened in for example Google Chrome by pressing F12)

like image 176
leroydev Avatar answered Oct 26 '22 22:10

leroydev


Version 4 breaking changes

Meanwhile you should use fire.

canvas.fire('object:modified');

In the observabile mixin observe, stopObserving, trigger are removed. Keep using on, off, fire. Those are shorter and also all our documentation refer to this kind of names.

For more details see Version 4 breaking changes.

like image 9
amp-sys Avatar answered Oct 26 '22 20:10

amp-sys