How to make object rotate with drag, how to get a rotate point around the origin use sin or cos?

17,203

There are two problems with your approach:

  1. The origin shouldn't be where the user clicked (that is the handle), but a fixed point in your div:

    target_wp=$(e.target).closest('.draggable_wp');
    //var o_x = e.pageX, o_y = e.pageY; // origin point
    var o_x = target_wp.offset().left,
        o_y = target_wp.offset().top; // origin point
    

    You will use the clicked point also, but for something else (more later):

    var h_x = e.pageX, h_y = e.pageY; // clicked point
    

    Finally, the origin should be fixed (i.e. should not change between rotations). One way of doing so is preserving it as a data attribute (there are other options though):

    if ( !target_wp.data("origin") )
        target_wp.data("origin", { left:target_wp.offset().left,
                                   top:target_wp.offset().top    });
    var o_x = target_wp.data("origin").left, 
        o_y = target_wp.data("origin").top; // origin point
    

    Update: One good candidate for the origin is the CSS property transform-origin, if present - it should ensure that the mouse follow the handle as closely as possible. This is an experimental feature, however, so the actual resulsts may vary. P.S. I'm not sure setting it to 50% 50% is a good idea, since the transformation itself may vary the element's width and height, top and left.

  2. To find the angle, you should not call atan2 on the mouse point only, since it will only calculate the angle between that point and the top left corner of the page. You want the angle between that point and the origin:

    var s_rad = Math.atan2(s_y - o_y, s_x - o_x); // current to origin
    

    That'll lead you halfway, but it will still behave oddly (it will rotate around the element origin, but not following the handle as you expect). To make it follow the handle, you should adjust the angle in relation to the clicked point - which will serve as a base for the amount to rotate:

    s_rad -= Math.atan2(h_y - o_y, h_x - o_x); // handle to origin
    

    After that you get the rotation working (for one user iteration at least).

You'll notice the handle does not follow the mouse precisely, and the reason is the choice of the origin point - defaulting to the element's top/left corner. Adjust it to somewhere inside the element (maybe using a data- attribute) and it should work as expected.

However, if the user interacts with the handle multiple times, it's not enough to just set the rotation angle, you must update whatever it was during the last iteration. So I'm adding a last_angle var that will be set on the first click and then added to the final angle during drag:

// on mousedown
last_angle = target_wp.data("last_angle") || 0;

// on mousemove
s_rad += last_angle; // relative to the last one

// on mouseup    
target_wp.data("last_angle", s_rad);

Here's the final working example. (Note: I fixed the nesting of your mouse handlers, so they don't get added again after each click)

$(function () {
    var dragging = false,
        target_wp,
        o_x, o_y, h_x, h_y, last_angle;
    $('.handle').mousedown(function (e) {
        h_x = e.pageX;
        h_y = e.pageY; // clicked point
        e.preventDefault();
        e.stopPropagation();
        dragging = true;
        target_wp = $(e.target).closest('.draggable_wp');
        if (!target_wp.data("origin")) target_wp.data("origin", {
            left: target_wp.offset().left,
            top: target_wp.offset().top
        });
        o_x = target_wp.data("origin").left;
        o_y = target_wp.data("origin").top; // origin point
        
        last_angle = target_wp.data("last_angle") || 0;
    })

    $(document).mousemove(function (e) {
        if (dragging) {
            var s_x = e.pageX,
                s_y = e.pageY; // start rotate point
            if (s_x !== o_x && s_y !== o_y) { //start rotate
                var s_rad = Math.atan2(s_y - o_y, s_x - o_x); // current to origin
                s_rad -= Math.atan2(h_y - o_y, h_x - o_x); // handle to origin
                s_rad += last_angle; // relative to the last one
                var degree = (s_rad * (360 / (2 * Math.PI)));
                target_wp.css('-moz-transform', 'rotate(' + degree + 'deg)');
                target_wp.css('-moz-transform-origin', '50% 50%');
                target_wp.css('-webkit-transform', 'rotate(' + degree + 'deg)');
                target_wp.css('-webkit-transform-origin', '50% 50%');
                target_wp.css('-o-transform', 'rotate(' + degree + 'deg)');
                target_wp.css('-o-transform-origin', '50% 50%');
                target_wp.css('-ms-transform', 'rotate(' + degree + 'deg)');
                target_wp.css('-ms-transform-origin', '50% 50%');
            }
        }
    }) // end mousemove
    
    $(document).mouseup(function (e) {
        dragging = false
        var s_x = e.pageX,
            s_y = e.pageY;
        
        // Saves the last angle for future iterations
        var s_rad = Math.atan2(s_y - o_y, s_x - o_x); // current to origin
        s_rad -= Math.atan2(h_y - o_y, h_x - o_x); // handle to origin
        s_rad += last_angle;
        target_wp.data("last_angle", s_rad);
    })
})
.draggable_wp {
    position: absolute;
    left: 150px;
    top: 150px;
}
.el {
    width: 25px;
    height: 50px;
    background-color: yellow;
}
.handle {
    position: absolute;
    left:0;
    top:-75;
    width: 25px;
    height: 25px;
    background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="draggable_wp">
    <div class="el"></div>
    <div class="handle"></div>
</div>
Share:
17,203
user1775888
Author by

user1775888

Updated on June 18, 2022

Comments

  • user1775888
    user1775888 almost 2 years

    I've been searching long time, but can't find a better way solve my problem,
    make div draggable, rotate and resize by each handle like these 2 example 1 2,, now it can be draggable, but rotate..

    Regarding Prasanth K C, Chango, Yi Jiang ..'s answer, these code maybe not correct,
    1. it should have a rotate point around the origin.
    2. need to consider radius.

    But I don't know how to use sin or cos here to make rotate consider radius?
    Any suggestion will be be appreciated. http://jsfiddle.net/tBgLh/8/

    var dragging = false, target_wp;   
    $('.handle').mousedown(function(e) {
        var o_x = e.pageX, o_y = e.pageY; // origin point
        e.preventDefault();
        e.stopPropagation();
        dragging = true;
        target_wp=$(e.target).closest('.draggable_wp');
    
        $(document).mousemove(function(e) {
            if (dragging) {
                var s_x = e.pageX, s_y = e.pageY; // start rotate point
                if(s_x !== o_x && s_y !== o_y){ //start rotate
                    var s_rad = Math.atan2(s_y, s_x);
                    var degree = (s_rad * (360 / (2 * Math.PI)));
                    target_wp.css('-moz-transform', 'rotate(' + degree + 'deg)');
                    target_wp.css('-moz-transform-origin', '50% 50%');
                    target_wp.css('-webkit-transform', 'rotate(' + degree + 'deg)');
                    target_wp.css('-webkit-transform-origin', '50% 50%');
                    target_wp.css('-o-transform', 'rotate(' + degree + 'deg)');
                    target_wp.css('-o-transform-origin', '50% 50%');
                    target_wp.css('-ms-transform', 'rotate(' + degree + 'deg)');
                    target_wp.css('-ms-transform-origin', '50% 50%');
                }
            }
        })
        $(document).mouseup(function() {
            dragging = false
        })
    })// end mousemove
    

    html

    <div class="draggable_wp">
        <div class="el"></div>
        <div class="handle"></div>
    </div>
    
  • user1775888
    user1775888 over 11 years
    if I combine draggable code, rotate then drag move wp position, then rotate it will jump to another angle because origin point change? need to upadte the new point? jsfiddle.net/tBgLh/12
  • mgibsonbr
    mgibsonbr over 11 years
    Yes. The problem with rotate is that it changes the top-left position, so you can't rely on it to determine the correct origin point. That's why I saved it using data the first time the element was rotated. If you drag (or resize) the element, that origin must be updated to keep a correct result. (And BTW, I used the top-left position as origin, but for a more accurate value you should use the same as your CSS defined as x-transform-origin)
  • user1775888
    user1775888 about 11 years
    jsfiddle.net/tBgLh/14 I put code check target_wp top left after drag mouseup and save, then rotation but it still not work, should I try to set a var = target_wp transform-origin? but how to calculate?
  • mgibsonbr
    mgibsonbr about 11 years
    Your code is fine, the only problem was when you tried to access target_wp as a jQuery object - when you were using it as a regular element. Place this at the beginning of your onmousemove and it will work: target_wp = $(target_wp); (demo) I'd also suggest not reusing dragging for both rotation and translation: both codes are running at the same time, producing errors (check the console). In the example above, I created a new one for rotating - dragging2.
  • user1775888
    user1775888 about 11 years
    I made a resize function bind this rotate function but after rotate over 90 degree, I need to make something change in resize function. So is there any way to check the object rotate over 90 degree? I try to set if(degree<90 && degree> -90) in mousemove but seems the degree is not the right one to use here? I made a question and demo here could you please give me some suggestion, thank you very much.
  • David John Welsh
    David John Welsh about 11 years
    Been trying to implement this for a while, without much success. With your explanation, though, I totally understand the math behind it now. You've made it so clear and easy to follow. You should write tutorials! I wish I could upvote more than once....
  • Beginner
    Beginner almost 11 years
    @mgibsonbr can we make same think for android app using jquery and phonegap??.. i tried many things i found on SO but i was not able to achieve. can u provide any ideas r suggestions??.. thanks in advance
  • mgibsonbr
    mgibsonbr almost 11 years
    @Beginer sorry, but I know nothing about phonegap and very little about Android development... I'm afraid you'll have to ask a separate question.
  • aVC
    aVC over 9 years
    @mgibsonbr I came across this solution, and I was trying to add "draggable" feature. jsfiddle.net/tBgLh/234 The rotation becomes erratic with this. Could you please take a look at the fiddle?
  • mgibsonbr
    mgibsonbr over 9 years
    Every time you move the element, you have to update its stored origin, or the angle of rotation will still have the previous origin as reference. Here's an updated example. The parts changed were: 1) the last bit, where you defined draggable; 2) the mouseup - which was incorrectly triggering during the drag, but should only trigger when rotating.
  • aVC
    aVC over 9 years
    @mgibsonbr update: Just noticed, if you drag before rotating, the script crashes. I am checking whats happening.
  • mgibsonbr
    mgibsonbr over 9 years
    @aVC That's because there's no origin to update. Here, fixed: jsfiddle.net/tBgLh/238
  • aVC
    aVC over 9 years
    @mgibsonbr quick followup question. Do I have to store the origin in seperate variables, if I were have two of those div sets which can be dragged AND Rotated?
  • mgibsonbr
    mgibsonbr over 9 years
    @aVC Yes. The origin is the point around which the object will rotate. You could simply use the object's position (i.e. the top/left corner), but that makes the behavior of the handle "strange". There's no perfect solution however - this whole question is a big abuse of CSS3 transformations IMHO. This is just the best I could come up with.