Search code examples
jqueryjquery-uidrag-and-dropdraggable

jquery drag and rotate to angle


I am using jQuery UI to drag and drop an image. I also want to rotate the image 360 degrees so I can move and rotate it like in Photoshop. I am using the jQuery rotate plugin to rotate the image on click, but I want to select a corner and drag to rotate the image to any angle.

Live JS: http://jsfiddle.net/87jaR/

JavaScript code:

var test = 5;
$(function() 
{
    $('#rotate').draggable({ containment: 'frame' });
    $('#frame img').live('mousedown', function(event) 
    {
        test = test + 15;
        $(this).rotate({ angle: test });
    });
});

Solution

  • Pls check with this one, Fiddle http://jsfiddle.net/prasanthkc/frz8J/

    var dragging = false
    
    $(function() {
    var target = $('#target')
    target.mousedown(function() {
        dragging = true
    })
    $(document).mouseup(function() {
        dragging = false
    })
    $(document).mousemove(function(e) {
        if (dragging) {
    
            var mouse_x = e.pageX;
            var mouse_y = e.pageY;
            var radians = Math.atan2(mouse_x - 10, mouse_y - 10);
            var degree = (radians * (180 / Math.PI) * -1) + 90;
            target.css('-moz-transform', 'rotate(' + degree + 'deg)');
            target.css('-moz-transform-origin', '0% 40%');
            target.css('-webkit-transform', 'rotate(' + degree + 'deg)');
            target.css('-webkit-transform-origin', '0% 40%');
            target.css('-o-transform', 'rotate(' + degree + 'deg)');
            target.css('-o-transform-origin', '0% 40%');
            target.css('-ms-transform', 'rotate(' + degree + 'deg)');
            target.css('-ms-transform-origin', '0% 40%');
        }
    })
    

    })

    1) Here deg means degree, Either you can use rad for radians

    2) You can change the rotating point by changing transform-origin

    For Eg: transform-origin: 50% 50% will move the rotating point to center.