ronIDX ronIDX - 5 months ago 27
Javascript Question

FabricJS - Avoid triggering "canvas.on('mouse:up', function() { ... })" after object end moving

Using FabricJS I'm making a canvas with the possibility to add rectangle.
Once a rectangle is added to canvas, it can be dragged in any position.

My problem is that when I stop dragging a rectangle, the event:

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


is triggered, but this is an unwanted behavior.

How can I trigger the event:

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


only when is effectively clicked the left button mouse, and not also when I end dragging object?

Answer

You could do something like this:

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
});