使用曲线的.animate函数

7

首先看一下:

enter image description here

猫需要以曲线的方式移动到x处。(请看箭头)

当猫碰到x时,它应该停留10秒,然后再次以曲线的方式返回o,并重复此过程。

我尝试使用以下代码:

function curve() {
    $('#cat').delay(10000).animate({top: '-=20',left: '-=20'}, 500, function() {
        $('#cat').delay(10000).animate({top: '+=20', left: '+=20'}, 500, function() {
            curve();
        });
    });
}

curve();

但是猫的动作是这样的:

enter image description here

有没有方法让猫以这种曲线移动?


https://dev59.com/KXE95IYBdhLWcg3wmvGh - RightSaidFred
YUI还提供了曲线动画的支持。http://developer.yahoo.com/yui/examples/animation/control.html - Mike Christensen
3个回答

1

1

您可以使用缓动来实现这一点,通过进行复合运动:

function curve () {
    $('#cat').delay(10000).animate({top: "+=20px", left: "+=20px"}, {
      duration: 500, 
      specialEasing: {top: 'easeOutQuad', left: 'easeInQuad'}, 
      complete: function () { 
        $('#cat').animate({top: "-=20px", left: "+=20px"}, {
          duration: 500, 
          specialEasing: {top: 'easeInQuad', left: 'easeOutQuad'},
          complete: function() {
            // repeat the other way around.
          }});
      }
    });
}

根据jQuery文档,它适用于jQuery 1.4及以上版本,并且所提到的缓动效果需要jQuery UI(但仅需要Effect Core模块)。每个.animate()调用占据了完整圆形路径的四分之一,而反向easeInQuadeaseOutQuad使路径看起来像是一个圆形路径,而不是直线到达新位置。


嗨,matehat!我在错误控制台中得到了这个错误:Error: f.easing[e.animatedProperties[this.prop]] is not a function 源文件:file:///C:/Dokumente%20und%20Einstellungen/Administrator/Desktop/tyler/js/js/jquery-1.6.4.min.js 行号:4 - bernte
你可能需要包含jQuery UI(仅限Effects Core部分),特别是这个文件:file - matehat

0
一个现代的2021年答案。你不必使用jQuery来实现这个。但我假设你想要。你可以像这样结合使用流行的npm库popmotion(每周600k次下载)和jQuery:
// poo.el.animate({top: footerTop - horsePooHeight})

// your imports may vary - I'm using Angular, popmotion focuses more on Vue and React
import { cubicBezier } from 'popmotion'
declare const popmotion: any
const {tween, easing} = popmotion

const fling = cubicBezier(0, .42, 0, 1)
tween({from: 100, to: 200, duration: 400, ease: fling}).start((v) => $(el).css('top', v))
tween({from: 100, to: 300, duration: 400, ease: easing.linear}).start((v) => $(el).css('left', v))

其中el是一个jQuery元素。

好消息是,它在缓动方面拥有更强大的功能,允许曲线。坏消息是它有点复杂,但如果你能理解上面的代码,那么你就没问题了。

附言:我并不是说popmotion应该与jQuery一起使用。我只是说它可以。

再次附言:永远不要忘记耶稣爱你 :D

再再次附言:对于简单的动画效果,jQuery是可以胜任的,但是像这样的问题缺乏足够的关注和jQuery动画库的更新不足以证明,对于更复杂的动画效果,单独使用jQuery已经不再适用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接