Search code examples
javascriptcreatejseaseljs

Moving multiple objects simultaneously in createJS/easelJS


I've been using easelJS within the createJS framework for a project and have enjoyed it a lot until recently hitting a roadblock. I have multiple objects that I'd like to move simultaneously when one of the group is dragged. Here is my current situation:

enter image description here

What I'd like to do is when the red circle is moved, the red crosshairs would also move so that they appear to be "locked" to the circle. The same with the green circle.

I have been able to accomplish something very close to this by adding the circles and crosshairs to a container, as mentioned in the answers to this question:

Easeljs Scrollable Container

But the issue I encounter is that the container is actually a rectangle, such that I can click anywhere between the circle and crosshairs to move the various objects contained within the container. Instead I would like for the objects to be moved only when I click on a circle.

Does anyone have any idea how to accomplish this? Am I correct in thinking this can be accomplished somehow with easelJS containers?


Solution

  • Containers should be fine. You can turn off mouseEnabled on the cross-hair in order to make it ignore the mouse.

    You could also just store the offset for each cross-hair/circle, and just set the cross-hair position when the circle moves.

    Here is a quick demo: http://jsfiddle.net/lannymcnie/kah9of6e/

    // Set the offset when the circle is pressed
    circle.on("mousedown", function(e) {
        circle.offset = new createjs.Point(crosshair.x-circle.x, crosshair.y-circle.y);
    });
    
    // Add drag and drop to each shape
    circle.on("pressmove", handleDrag);
    crosshair.on("pressmove", handleDrag);
    
    function handleDrag(e) {
      // Move the target to the mouse
      e.target.x = e.stageX; e.target.y = e.stageY;
    
      // If the target is the circle, also move the cross-hair
      if (e.target == circle) {
        // Move the cross-hair
        crosshair.x = circle.x + circle.offset.x;
        x.y = circle.y + circle.offset.y;
      }
    }