Mousemove动画

时间:2014-05-15 16:34:00

标签: javascript jquery html5 animation

您好我正在努力实现这种效果http://mario.ign.com/modern-era/super-mario-3D-world没有鼠标移动我想通过某种缓和效果来实现它以使其平滑但实际上不知道如何实现de desaceleration效果,到目前为止我是什么已完成的是http://jsfiddle.net/xtatanx/8RB24/1/

var $container = $('#container');
var contWidth = $container.width();
var $point = $('.point');
var delay = 100;

$container.mousemove(function(e){
    clearTimeout(timer);

    var timer = setTimeout(function(){
        console.log(e.offsetX);
        $point.each(function(){
            if( e.offsetX > (contWidth - $point.width())){
                return;
            }
            var xp = $(this).position().left;
            xp += parseFloat((e.offsetX - xp)/ 20);
            $(this).css({
                left: xp
            });
        });
    }, delay);

});

但我认为动画并不像马里奥网站那样流畅,如果你们能帮助我提供资源或指导我实现这种效果,我会很感激。非常感谢你。

2 个答案:

答案 0 :(得分:2)

你的不稳定是因为它只在mousemove事件上运行。如果你把它分解成一个间隔(比如说每秒30帧),它会更加平滑。这样,即使鼠标停止,它也会继续缓和。

var $container = $('#container');
var contWidth = $container.width();
var $point = $('.point');
var delay = 100;
var decay = .1;

var intervalId;
var mouseX, mouseY;

//this function is called 30 times per second.
function ticker(){
     $point.each(function(){
         if( mouseX > (contWidth - $point.width())){
             mouseX = (contWidth - $point.width()); //instead of returning, just set the value to the max
         }
         var xp = $(this).position().left;
         xp += parseFloat((mouseX - xp) * decay); //using a decay variable for easier tweaking
         $(this).css({
            left: xp
         });
     });
}

//this interval calls the ticker function every 33 milliseconds
intervalId = setInterval(ticker, 33); //33 millisecond is about 30 fps  (16 would be roughly 60fps)

$container.mousemove(function(e){
    mouseX = e.offsetX; //store the current mouse position so we can reference it during the interval
    mouseY = e.offsetY;
});

答案 1 :(得分:1)

看看这个。不确定这是你想要的,但它确实是“一个”技巧。

$container.mousemove(function(e){

    var xp = e.clientX-offset;
    blue.css({
        left: xp+'px'
     });

});

http://jsfiddle.net/d65yan/8RB24/2/

查看.blue {} css 如果你想支持旧版本的moz和chrome,则需要一些vendro前缀,但是忘记即可达到版本9