How to trigger mouse:over event after a certain interval using fabricjs?

梦想与她 提交于 2019-12-12 07:00:13

问题


I want to trigger the mouse:over event only when the user hovers over an elements for more than a specific set interval (for example 200ms).

Currently I have used this example for adding the event "instantly": http://fabricjs.com/hovering

What is the best way to add a delay before that event is triggered?

Regards, Alex


回答1:


In your case I think you can use setTimeout function inside the mouse:over handler. This way you can put some delay before executing the code.

So what I did:

1) Use setTimeout inside mouse:over handler

2) save reference to the started timeout in var timeout;

3) use clearTimeout on timeout variable in mouse:out handler to prevent the code in mouse:over been executed if mouse is out before the delay is fully completed

(function() {
  var canvas = this.__canvas = new fabric.Canvas('c');
  fabric.Object.prototype.transparentCorners = false;
  
  var timeout;
  canvas.on('mouse:over', function(e) {
    if(!e.target) return false;
    
    timeout = setTimeout(function(){
      e.target.setFill('red');
      canvas.renderAll();
    }, 1000)
  });

  canvas.on('mouse:out', function(e) {
    if(!e.target) return false;
    
    /* clear the timeout so we make sure that mouse:over code will not execute if delay is not completed */
    clearTimeout(timeout);
    
    e.target.setFill('green');
    canvas.renderAll();
  });

  // add random objects
  for (var i = 15; i--; ) {
    var dim = fabric.util.getRandomInt(30, 60);
    var klass = ['Rect', 'Triangle', 'Circle'][fabric.util.getRandomInt(0,2)];
    var options = {
      top: fabric.util.getRandomInt(0, 300),
      left: fabric.util.getRandomInt(0, 300),
      fill: 'green'
    };
    if (klass === 'Circle') {
      options.radius = dim;
    }
    else {
      options.width = dim;
      options.height = dim;
    }
    canvas.add(new fabric[klass](options));
  }
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.16/fabric.js"></script>

<canvas id="c" width="300" height="300"></canvas>

The current timeout that I'm using in this code snippet is 1000 milliseconds = 1 second. You can adjust this in the setTimeout function. I hope this was helpful for you, let me know if something is unclear.



来源:https://stackoverflow.com/questions/45165039/how-to-trigger-mouseover-event-after-a-certain-interval-using-fabricjs

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