旋转鼠标轻松跟随

时间:2015-12-02 16:14:30

标签: jquery

我建了一个menupage,我按照鼠标的方式在中间旋转图像,如下所示:

http://jsfiddle.net/JqBZb/

$(document ).mousemove(function( event ) {

    var mouseX = event.pageX;
    var mouseY = event.pageY;
    var offsetX = $(window).width()/2;
    var offsetY = $(window).height()/2;
    var radian = Math.atan2(mouseX - offsetX, mouseY - offsetY);
    var deg = (radian * (180/Math.PI) * -1) + 180;

$('#compassIn').css({
        '-webkit-transform': 'translateY(-50%) translateX(-50%) rotateZ(' + deg + 'deg)',
        '-moz-transform': 'translateY(-50%) translateX(-50%) rotateZ(' + deg + 'deg)',
        '-ms-transform': 'translateY(-50%) translateX(-50%) rotateZ(' + deg + 'deg)',
        '-o-transform': 'translateY(-50%) translateX(-50%) rotateZ(' + deg + 'deg)',
        'transform': 'translateY(-50%) translateX(-50%) rotateZ(' + deg + 'deg)',
    }); 
}); 

问题是如何添加延迟和缓动以使旋转平滑。

谢谢!

1 个答案:

答案 0 :(得分:0)

简单的CSS过渡可以在这里创造奇迹。请参阅示例:

img {transition: transform 0.2s ease-in-out}

http://jsfiddle.net/JqBZb/622/

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);
}
#apDiv1 {
    position:absolute;
    width:400px;
    height:327px;
    z-index:1;
    left: 105px;
    top: 98px;
}
img {transition: all 0.2s ease-in-out; width: 50px; height: auto}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="apDiv1"><img src="https://upload.wikimedia.org/wikipedia/commons/f/ff/Finger-pointing-icon.png" class="image"/> <br>
    (Not actual picture I'm trying to rotate, but it'll do for now)
</div>

当然,你可以调整时间,缓和等等。你一定要处理从359到0的旋转,反之亦然。