Search code examples
javascriptmouseeventpaperjs

In PaperJS how to link onMouseUp event to origin of onMouseDown event when mouse has moved away from item


In my PaperJS project I have a bunch of objects that have a circle Path associated with them. These paths each have mouse functions.

What I'd like to do is to create links between two circles when clicking on one, dragging the mouse, and releasing the mouse button on another circle.

For this I use the PaperJS onMouseDown and onMouseUp events, implemented like this inside the object:

function CircleObj() { // the object constructor
   this.circle = new Path(...);
   this.circle.onMouseDown = function(event) {
      //eventstuff
   }
}

where this.circle is the circle Path.

The problem is that when I release the mouse button it is no longer linked to the circle, and so the onMouseUp function doesn't execute until I click on the actual circle again. This therefore doesn't allow you to drag and drop over the other circle, since the 'drop' action doesn't register.

How can I have the onMouseUp event register and be linked to the circle where the onMouseDown event took place?


Solution

  • If you want to keep your mouse events tied to your constructor, I think it would be easiest to keep the initial point in a global variable. It's certainly cleaner than adding and removing a Tool Event to the view and checking to see if the hit object is a circle and not a line or other object.

    var firstPoint = null;
    
    function circleObj(p) {
        this.circle = new Path.Circle({
           center: p,
           radius: 20,
           fillColor: 'red'
        });
        this.circle.onMouseDown = function(event) {
                firstPoint = this.position;
        }
        this.circle.onMouseUp = function(event) {
            if (firstPoint !== null){
                var path = new Path.Line({
                    from: firstPoint,
                    to: this.position,
                    strokeColor: 'black',
                    strokeWidth: 40,
                    strokeCap: 'butt'
                });
                path.sendToBack();
                firstPoint = null;
            }
        }
    }
    
    function onMouseDown(event){
        if (!event.item){
            circleObj(event.point);
            firstPoint = null;
        }
    }