Wednesday 18 July 2018

Drag elements simultaneously in a uniform circular motion

I want to achieve simultaneously move with mouse drag of multiple divs in a uniform circular motion.

Please review my fiddle. The issue is when I drag Div number "3" or "1" it always focus on the div "2". Also, the time of rotation of the divs using "transform" the position of the mouse cursor and the divs are mismatched.

HTML

<div class="a" id="d">
  <div class="sm-1">1</div>
  <div class="sm-2">2</div>
  <div class="sm-3">3</div>
</div>

CSS

.a {
  height: 300px;
  width: 300px;
  border: 3px solid orange;
  border-radius: 50%;
  margin: 30px auto;
  position: relative
}

.sm-1,
.sm-2,
.sm-3 {
  position: absolute;
  height: 100px;
  width: 100px;
  border: 3px solid black;
  border-radius: 50%;
  text-align: center;
}

.sm-1 {
  top: 70%;
  background: red;
}

.sm-2 {
  top: 50%;
  right: -33px;
  background: green;
}

.sm-3 {
  top: -33px;
  right: 50%;
  background: blue;
}

JS

$(document).ready(function() {

  function rotateOnMouse(e, pw, elm) {
    var offset = pw.offset();
    var center_x = (offset.left) + ($(pw).width() / 2);
    var center_y = (offset.top) + ($(pw).height() / 2);
    var mouse_x = e.pageX;
    var mouse_y = e.pageY;
    var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
    var degree = (radians * (180 / Math.PI) * -1) + 100;

    $(pw).css({
      '-moz-transform': 'rotate(' + degree + 'deg)',
      '-webkit-transform': 'rotate(' + degree + 'deg)',
      '-o-transform': 'rotate(' + degree + 'deg)',
      '-ms-transform': 'rotate(' + degree + 'deg)'
    });

    $(elm).css({
      '-moz-transform': 'rotate(-' + degree + 'deg)',
      '-webkit-transform': 'rotate(-' + degree + 'deg)',
      '-o-transform': 'rotate(-' + degree + 'deg)',
      '-ms-transform': 'rotate(-' + degree + 'deg)'
    });
  }

  $('.a').mousedown(function(e) {
    e.preventDefault();
    document.onmouseup = closeDragElement;

    document.onmousemove = function(e2) {
      rotateOnMouse(e2, $('.a'), $('div[class^=sm-]'));
    };
  });

  function closeDragElement() {
    document.onmouseup = null;
    document.onmousemove = null;
  }
});

http://jsfiddle.net/1h3ps54c/

Thank you.



from Drag elements simultaneously in a uniform circular motion

No comments:

Post a Comment