开发者

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 app开发者_Go百科reciated. 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>


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);
}


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.


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜