在requestAnimationFrame上添加缓动

eng*_*nws 4 javascript jquery animation easing

我需要重现与此处相同的效果:http://www.chanel.com/fr_FR/mode/haute-couture.html =对鼠标移动事件的滑动效果.

我只需要动画部分的一些帮助.

    function frame() {
      $('.images-gallery').css({
        'transform': 'translateX('+ -mouseXPerc +'%)'
      });
      requestAnimationFrame(frame);
    }

    requestAnimationFrame(frame);
    $(document).on('mousemove',function(e){
      mouseXPerc = e.pageX/containerWidth*100;

    });
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所做的.它的工作原理,但你可以想象,它是非常原始的,我需要一些缓和.如何编辑我frame() function以使事情变得更顺畅?

编辑:我不能使用CSS转换/动画,因为我更改requestAnimationFrame上的值(每1/30秒).

TKo*_*KoL 9

我想我找到了答案.它基于这个库

首先,我只是从该网站获取一个功能

function inOutQuad(n){
    n *= 2;
    if (n < 1) return 0.5 * n * n;
    return - 0.5 * (--n * (n - 2) - 1);
};
Run Code Online (Sandbox Code Playgroud)

然后,我会使用示例代码的修改形式,就像这样

function startAnimation(domEl){
    var stop = false;

    // animating x (margin-left) from 20 to 300, for example
    var startx = 20;
    var destx = 300;
    var duration = 1000;
    var start = null;
    var end = null;

    function startAnim(timeStamp) {
        start = timeStamp;
        end = start + duration;
        draw(timeStamp);
    }

    function draw(now) {
        if (stop) return;
        if (now - start >= duration) stop = true;
        var p = (now - start) / duration;
        val = inOutQuad(p);
        var x = startx + (destx - startx) * val;
        $(domEl).css('margin-left', `${x}px`);
        requestAnimationFrame(draw);
    }

    requestAnimationFrame(startAnim);
}
Run Code Online (Sandbox Code Playgroud)

我可能会改变计算"停止"的方式,我可能会写一些东西以确保它结束destx等,但这是基本格式

这个jsfiddle中显示它

我真的为这个感到自豪.我一直想要解决这个问题.很高兴我有理由.


Luk*_*uka 0

您可以创建自己的ease函数并在函数中使用它frame

var ease = function() {
    var x = 0;
    return function(x_new) {
        x = (x_new+x)*.5;
        return x;
    }
}();

function frame() {
  $('.images-gallery').css({
    'transform': 'translateX('+ -ease(mouseXPerc) +'%)'
  });
  requestAnimationFrame(frame);
}

requestAnimationFrame(frame);
$(document).on('mousemove',function(e){
  mouseXPerc = e.pageX/containerWidth*100;

});
Run Code Online (Sandbox Code Playgroud)