在 requestAnimationFrame 上添加缓动

问题描述 投票:0回答:3

我需要重现与这里相同的效果: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;

    });

这是我到目前为止所做的。 它按预期工作,但正如你可以想象的那样,它非常原始,我需要一些缓解。如何编辑我的

frame() function
以获得更流畅的效果?

编辑:我无法使用 CSS 过渡/动画,因为我更改 requestAnimationFrame 上的值(每 1/30 秒)。

javascript jquery animation easing
3个回答
17
投票

我想我已经为你找到了答案。它基于这个库

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

function inOutQuad(n){
    n *= 2;
    if (n < 1) return 0.5 * n * n;
    return - 0.5 * (--n * (n - 2) - 1);
};

然后,我将使用示例代码的修改形式,如下所示

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

我可能会改变“停止”的计算方式,我可能会写一些东西来确保它以

destx
结束,等等,但这是基本格式

this jsfiddle

中显示它

我真的为这个感到有点自豪。我有一段时间一直想弄清楚这个问题。很高兴我有理由这么做。


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;

});

0
投票

基于 fast-ease.js 但无法中断动画

function inOutQuad(n){
    n *= 2;
    if (n < 1) return 0.5 * n * n;
    return - 0.5 * (--n * (n - 2) - 1);
};

function animate(callback, ease, duration, from, to) {
    var id;
    var start = performance.now();
    var end = start + duration;
    function frame(now) {
        var delta = now - start;
        if (delta >= duration) return cancelAnimationFrame(id);
        callback(from + (to - from) * ease(delta / duration));
        id = requestAnimationFrame(frame);
    }
    id = requestAnimationFrame(frame);
};

© www.soinside.com 2019 - 2024. All rights reserved.