James
James

Reputation: 65

Image rotate to mouse using Jquery and CSS

I have a compass image and am trying to get the needle to follow the mouse around the page, exactly how the images are rotated in the following demo but without having to shift and click. I'm having trouble breaking down that code however, so any help would be most appreciated. Thanks in advance.

http://www.elated.com/res/File/articles/development/javascript/jquery/smooth-rotatable-images-css3-jquery/

The images are simply wrapped in a div

<div id="content">
<img id="compass" src="compass.png"/>
<img id="needle" src="needle.png"/>
</div>

Upvotes: 3

Views: 8090

Answers (3)

aperture
aperture

Reputation: 2895

Try this: https://jsfiddle.net/x2d8pmub/

var img = $('.image');
if(img.length > 0){
    var offset = img.offset();
    function mouse(evt){
        var center_x = (offset.left) + (img.width()/2);
        var center_y = (offset.top) + (img.height()/2);
        var mouse_x = evt.pageX; var mouse_y = evt.pageY;
        var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
        var degree = (radians * (180 / Math.PI) * -1) + 90; 
        img.css('-moz-transform', 'rotate('+degree+'deg)');
        img.css('-webkit-transform', 'rotate('+degree+'deg)');
        img.css('-o-transform', 'rotate('+degree+'deg)');
        img.css('-ms-transform', 'rotate('+degree+'deg)');
    }
    $(document).mousemove(mouse);
}

Upvotes: 5

zzzzBov
zzzzBov

Reputation: 179264

Rather than type up a long answer about how to do CSS rotations, I'll just link you to this good writeup.

As for figuring out the angle to rotate by, you'll need to know the position of the center of the compass, and the location of the mouse. Bind a mousemove event on the document to update the compass when the mouse is moving.

Find the difference in x and y:

dx = mouse.x - compass.x;
dy = mouse.y - compass.y;

Assuming that rotation goes clockwise, and that 0° is vertical (this will reverse the Math.atan2 arguments), tan(Θ) = dx / dy.

Θ = arctan( dx / dy );

or in JS

angle = Math.atan2( dx, dy );

Let me know if I've messed up the order of subtraction for dx & dy.

Upvotes: 1

Michele
Michele

Reputation: 3

you can use the function of css3 to rotate the div

img {
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2);
}

and you can use the method "draggable()" of jQuery UI to move it :)

Upvotes: 0

Related Questions