How do i trigger mouse events in fabric.js to simulate mouse actions?

佐手、 提交于 2019-12-02 01:28:25

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 = new MouseEvent("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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.js"></script>
<canvas id="c" width="300" height="200"></canvas>
<button id="testClick">Deselect</button>

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!