Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag two images together, but limit one's movement to vertical axis

I'd like to move two images together on a page.The layout of this is the following:

|1.1|--2.1--|
|1.2|--2.2--|
|1.3|--2.3--|
|1.4|--2.4--|

So the images are next to each other, cells that start with '1' belong to the first image, those that start with '2' belong to the second image.

When I drag any of the images the expected behaviour is that both images move, but image 1 only on the vertical axis. (So it remains on the left, but might move up or down as much as image 2. This image will be used as a sort of header, and needs to be visible on the left all the time, but needs to be vertically in sync with image 2.), image 2 can move along both axes.

In the example this means that the 1.1 part of the first image will always be in line with the 2.1 part of the second image.

Is there any JS framework that might support this? I've tried using fabric JS, but when I cap the coordinates in an event handler it becomes unbelievably slow.

This code is what I've tried, it doesn't do exactly what I've described, this restricts the movement to a rectangle, but the theory behind it is the same.

canvas.on("object:moving", function() {
  var top = movingBox.top;
  var bottom = top + movingBox.height;
  var left = movingBox.left;
  var right = left + movingBox.width;

  var topBound = boundingBox.top;
  var bottomBound = topBound + boundingBox.height;
  var leftBound = boundingBox.left;
  var rightBound = leftBound + boundingBox.width;

  movingBox.setLeft(Math.min(Math.max(left, leftBound), rightBound - movingBox.width));
  movingBox.setTop(Math.min(Math.max(top, topBound), bottomBound - movingBox.height));
});
like image 935
Kompi Avatar asked Jul 27 '15 13:07

Kompi


1 Answers

This can be achieved easily using jQuery UI, with two separate draggable elements, one is constrained to move only on the 'Y' axis, and both update each other 'top' value upon dragging.

** HTML **

<img id="img1" src="http://placehold.it/100X100" />
<img id="img2" src="http://placehold.it/100X100" />

** JS **

var img1 = $('#img1'),
    img2 = $('#img2');

img1.draggable({
    axis: 'y',
    drag: function(event, ui){
        img2.css('top', ui.position.top+'px');
    }
});
img2.draggable({
    drag: function(event, ui){
        img1.css('top', ui.position.top+'px');
    }
});

Check it working in this JsFiddle :-)

like image 161
Ronen Cypis Avatar answered Oct 17 '22 01:10

Ronen Cypis