user1261242
user1261242

Reputation: 11

Jquery-rotate cursor angle

I need rotate arrow with Jquery-rotate, but i dont know cursor's angle :( I try calculate it, but script not work.

I want result like this http://www.lonhosford.com/content/html5/canvas/rotate_to_mouse.html

<script type="text/javascript">
//<![CDATA[
    $(document).ready(function(){
        function diff(x, y) {
            var a = (x * Math.PI / 180) - Math.PI;
            var b = (y * Math.PI / 180) - Math.PI;
            return Math.atan2(Math.sin(b - a), Math.cos(b - a)) * (180 / Math.PI);
        }
        $('body').mousemove(function(e){
            var x = e.pageX;
            var y = e.pageY;
            var myAngle = diff(x, y);
            $("#image").rotate(myAngle);
        });         
    });
//]]>
</script>

Upvotes: 1

Views: 3286

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

If you look at the source code of the example you posted you will find

update: function()
    {
        // Distance from mouse x and center of canvas.
        this._dx = mouse.x - this.centerX; 
        // Distance from mouse y and center of canvas.
        this._dy = mouse.y - this.centerY; 
        // Radians for the canvas rotate method.
        this._radians = Math.atan2(this._dy,this._dx);
    }

To adapt this code for your own needs try

function diff(x, y) {
    var centerItem = $('imageid'),
        centerLoc = centeItem.offset();
    var dx = x - centerLoc.left + (centerItem.width() / 2);
        dy = y - centerLoc.top + (centerItem.height() / 2);
    return Math.atan2(dy, dx) * (180 / Math.PI);
}

example at http://jsfiddle.net/gaby/xWtKc/1/

Upvotes: 1

Related Questions