Skip to content Skip to sidebar Skip to footer

Fabric.js: Bind Event To Background Image

I'm trying to bind an event to a background image: var imgInstance = fabric.Image.fromURL(path, function(oImg) { oImg.on('selected', function() { alert(); });

Solution 1:

It doesn't seem like you can add events to the background image... but the canvas does emit events and if you click the canvas and no target is set then they must be clicking the background. Background image are not forced to take up the whole background but I'm not sure reasons to not make it take up the whole background.

You do get the mouse event passed in though so if the background image does not take up the whole background you could do that math and figure out where they clicked.

window.canvas = new fabric.Canvas('c', { selection: false, preserveObjectStacking:true });

fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(o) {
	canvas.setBackgroundImage(o, canvas.renderAll.bind(canvas), {
    top: 0,
    left: 0
  });
});

canvas.on('mouse:down', function(options) {
  if (!options.target) {
  	console.log('target is null')
  
  }
});


canvas.add(new fabric.Rect({ 
  left: 100, 
  top: 100, 
  width: 50, 
  height: 50, 
  fill: '#faa', 
  originX: 'left', 
  originY: 'top',
  centeredRotation: true
}));
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script><canvasid="c"width="600"height="600"></canvas>

Post a Comment for "Fabric.js: Bind Event To Background Image"