Skip to content Skip to sidebar Skip to footer

How Do I Trigger Mouse Events In Fabric.js To Simulate Mouse Actions?

I'm able to get the jquery response on the triggering but the fabric canvas is not acting on the event. I expect this fiddle to deselect the IText element: fiddle I know the fabric

Solution 1:

It won't be enough to just trigger events via Fabric's trigger. The events that Fabric objects emit are not used to trigger internal logic, so firing them won't do any good unless you want to trigger your own event handlers.

I'm not familiar with jQuery's events, but you can do just as well with the standard JS MouseEvent constructor. Just make sure you're:

  • firing the appropriate event type (i.e. 'mousedown', not 'click')
  • dispatching it on the appropriate DOM element (i.e. Fabric's upper canvas, accessible via canvas.upperCanvasEl)
  • setting the event's clientX/clientY instead of pageX/pageY

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

canvas.on({"mouse:down": function(e) {
  console.log("Mouse down", e.e.clientX, e.e.clientY);
  canvas.renderAll();
}});

document.querySelector('#testClick').onclick = function() {
  var evt = newMouseEvent("mousedown", {
    clientX: 15,
    clientY: 15
  });
  canvas.upperCanvasEl.dispatchEvent(evt);
  // same as://document.querySelector(".upper-canvas").dispatchEvent(evt);
}


/*************** TEXT ****************/var text = new fabric.IText('FaBric.js', {
  fontSize: 40,
  textAlign: 'center',
  fontWeight: 'bold',
  left: 128,
  top: 128,
  angle: 30,
  originX: 'center',
  originY: 'center',
  shadow: 'blue -5px 6px 5px',
  styles: {
    0: {
      0: {
        fontSize: 60,
        fontFamily: 'Impact',
        fontWeight: 'normal',
        fill: 'orange'
      }
    }
  }

});

text.setSelectionStyles({
  fontStyle: 'italic',
  fill: '',
  stroke: 'red',
  strokeWidth: 2
}, 1, 5);
canvas.add(text);
canvas.setActiveObject(text);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.js"></script><canvasid="c"width="300"height="200"></canvas><buttonid="testClick">Deselect</button>

Solution 2:

Here is a working fork of your fiddle: https://jsfiddle.net/y74h38av/

The main problem in your existing code is that you are confusing the jQuery event API with the Fabric event API. The Fabric canvas object does not accept a jQuery event object. Also, note the syntactical differences between the two APIs. jQuery uses mousedown while Fabric uses mouse:down. You access the Fabric event API via the event method directly on a Fabric object. If you try to wrap the Fabric object in a jQuery object, like you do here, jQuery(test).trigger(e);, it will not work.

I hope this helps!

Post a Comment for "How Do I Trigger Mouse Events In Fabric.js To Simulate Mouse Actions?"