【问题标题】:FabricJS - Avoid triggering "canvas.on('mouse:up', function() { ... })" after object end movingFabricJS - 避免在对象结束移动后触发“canvas.on('mouse:up', function() { ... })”
【发布时间】:2016-11-01 10:22:31
【问题描述】:

使用 FabricJS,我正在制作一个可以添加矩形的画布。 将矩形添加到画布后,可以将其拖动到任意位置。

我的问题是当我停止拖动一个矩形时,事件:

canvas.on('mouse:up', function(element) { ... });

被触发,但这是不受欢迎的行为。

如何触发事件:

canvas.on('mouse:up', function(element) { ... });

仅当有效单击鼠标左键时,而不是当我结束拖动对象时?

【问题讨论】:

    标签: javascript events canvas listener fabricjs


    【解决方案1】:

    你可以这样做:

    var _isDragging = false;
    var _isMouseDown = false;
    
    canvas.on('mouse:down', function () {
        _isMouseDown = true;
        // other stuff
    });
    
    canvas.on('mouse:move', function () {
        _isDragging = _isMouseDown;
        // other stuff
    })
    
    canvas.on('mouse:up', function(element) {
        _isMouseDown = false;
        var isDragEnd = _isDragging;
        _isDragging = false;
        if (isDragEnd) {
            // code for drag complete
        } else {
            // code for no drag mouse up
        }
        // code for both
    });
    

    【讨论】:

      【解决方案2】:

      应避免添加mouse:move 侦听器
      因为每个像素都会触发移动事件
      fabric.js event inspector sample

      在大多数情况下,您只需要比较
      mousedownmouseup的两个点击位置

      fabricjs_obj
      .on('mousedown', function (event) {
          event.target.dragStart = event.pointer
      })
      
      fabricjs_obj
      .on('mouseup', function (event) {
          const a = event.target.dragStart
          const b = event.pointer
          const obj = event.target
          if (a.x != b.x || a.y != b.y) {
              console.log('obj dragged: '+obj)
              return // stop event handler
          }
          console.log('obj clicked: '+obj)
          // process click event
      })
      

      【讨论】:

        猜你喜欢
        • 2016-09-21
        • 2015-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-07
        • 1970-01-01
        • 2017-02-02
        相关资源
        最近更新 更多