pthalacker
pthalacker

Reputation: 2124

What can I get a handle on the target of a fabric js event?

In this fabricjs tutorial section it says putting listeners right on an object like so

var rect = new fabric.Rect({ width: 100, height: 50, fill: 'green' });
   rect.on('selected', function() {
   console.log('selected a rectangle');
});

That is fine, but I don't want to log a string to the console. I want to manipulate the rectangle. Specifically the rectangle isn't selectable by default and based on application state, I need to make it selectable.

I can't figure out how to get a handle on the rectangle from inside the event handler. How to do that escapes me.

Upvotes: 0

Views: 2684

Answers (1)

Swapnil Jain
Swapnil Jain

Reputation: 1516

In the example you gave, you have attached the event to the object itself. So you can access the object using this or the variable name (which is rect in your case). Here is an example

var rect = new fabric.Rect({ width: 100, height: 50, fill: 'green' });
rect.on('selected', function() {
   console.log(this);
   this.set({width:200});
});

Alternatively, if you attach it to the canvas so that it listens to all the object:selected events, you can access the object at which the event occurred like this:

var rect = new fabric.Rect({ width: 100, height: 50, fill: 'green' });
canvas.on('object:selected', function (e) {
    console.log('selected a rectangle');
    e.target.set({width:200});
});

Upvotes: 3

Related Questions