Fabric.js: Is there any way to have a clickable object on canvas and link it to external files / urls

Created on 10 Dec 2016  路  3Comments  路  Source: fabricjs/fabric.js

Hi,

I would like to create a link or object on canvas onclick of which should open a file or url.
For example, if I'm annotating an image and I want to put some context info at a particular point in the image which can be a file or an url (ex. Wiki links). Is there any way I can do it? May be by creating a custom object? Can you please provide some guidance?

Most helpful comment

you have to hookup a mouse:down event on the object.

object.on('mouse:down', function(opt) {
  // inside opt you found `e`
  // you should be able to calculate where you clicked
  var pointClicked = opt.target.canvas.getPointer(opt.e);
});

All 3 comments

You can try to detect a click or double click on the object using the events. And open the url (cf demo1).
Or you can make an invisible div with a onClick action and move this div on the object (cf demo2).

demo1 : http://fabricjs.com/events
demo2 : http://fabricjs.com/interaction-with-objects-outside-canvas

you have to hookup a mouse:down event on the object.

object.on('mouse:down', function(opt) {
  // inside opt you found `e`
  // you should be able to calculate where you clicked
  var pointClicked = opt.target.canvas.getPointer(opt.e);
});

I see an error sometimes so I think it is better to use if (options.target) first :

canvas.on('mouse:down', function(options) {
  if (options.target) {
    console.log('an object was clicked! ', options.target.type);
    var pointClicked = opt.target.canvas.getPointer(opt.e);
    console.log(pointClicked);
    if(options.target.id){
        // if you set an ID you can use it in a switch or if command
        // it worth noting you have to tell it to keep id's when using canvas.toJSON()
        // like this canvas.toJSON(['id'])
        console.log('ID:', options.target.id);
    }
  } else {
    console.log('not a target');
  }
});
Was this page helpful?
0 / 5 - 0 ratings