Mobilpadde
Mobilpadde

Reputation: 1881

Rotating on mouse move

Something I've wanted to learn for quite a time now, but haven't been able to figure out.

http://jsfiddle.net/Mobilpadde/Xt7ag/

Then you move the mouse, it follows, which is the easy part, but I want to rotate too, like always look in the direction of the mouse, but not so static, more like, if you move your mouse up, it should kinda rotate first, and then you move the mouse further away, it should begin to follow again (If you know what I mean).

Is that something simple to do, or 3k lines? (Or maybe a jQuery plugin?)

Upvotes: 2

Views: 7004

Answers (3)

Tats_innit
Tats_innit

Reputation: 34117

Hiya I got it something more closer by using an old post of mine : demo http://jsfiddle.net/Z3pGQ/3/

I am still working, will flick you more smoother version or if you can improve before me:

Old post: Rotating an element based on cursor position in a separate element

Hope it helps, I am trying to make it smoother now, cheers

Sample code

$(document).ready(function() {
    $(document).mousemove(function(e) {
        $(".firefly").css({
            "top": (e.pageY * 2) + "px",
            "left": (e.pageX * 2 + 130) + "px"
        });
    })
})
var img = $(".firefly");
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);
}​

Image

enter image description here

Upvotes: 6

Kyeotic
Kyeotic

Reputation: 19857

This is going to involve a lot more math than I want to do right now, but you can apply rotations with css easily. Here are the properties for mozilla and webkit, you can see the rest of the (IE,Opera...) at this page. Here is your function with a 120deg rotation applied. You will still need to calculate the proper rotation, and adjust the left and top accordingly.

$(document).mousemove(function(e){
                $(".firefly").css({
                    "top":(e.pageY*2)+"px",
                    "left":(e.pageX*2+130)+"px",
                    "-moz-transform": "rotate(120deg)",
                    "-webkit-transform": "rotate(120deg)"});
            })

Upvotes: 0

Related Questions