如何在一定间隔后使用fabricjs触发mouse:over事件? [英] How to trigger mouse:over event after a certain interval using fabricjs?

查看:330
本文介绍了如何在一定间隔后使用fabricjs触发mouse:over事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅当用户将鼠标悬停在元素上的时间超过特定的设置间隔(例如200ms)时,我才想触发mouse:over事件.

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).

当前,我已使用此示例立即"添加事件: http://fabricjs.com/hovering

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?

关于, 亚历克斯

推荐答案

在您的情况下,我认为您可以使用 mouse:over处理程序中的="nofollow noreferrer"> setTimeout 函数.这样,您可以在执行代码之前稍加延迟.

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.

那我做了什么:

1)在mouse:over处理程序中使用setTimeout

1) Use setTimeout inside mouse:over handler

2)将对启动超时的引用保存在var timeout;

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

3)在timeout上使用 clearTimeout mouse:out处理程序中的变量,以防止在完全完成延迟之前将鼠标移出mouse:over中的代码

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>

我在此代码段中使用的当前超时为1000毫秒= 1秒.您可以在setTimeout功能中进行调整.希望这对您有所帮助,如果有不清楚的地方,请通知我.

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.

这篇关于如何在一定间隔后使用fabricjs触发mouse:over事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆