随机 JQuery 的 .animate 缓动
Random JQuery's .animate easing
我已经找了一段时间了,但似乎找不到我需要的东西。 我知道你可以自定义缓动,但我不知道怎么做。 我正在赛马(JQuery 移动所有的马)。我需要它们以随机速度运行,但需要在给定的持续时间内完成动画。例如:
马1:
[0-1-3-4-5-4-4-5-3-2-8-9-8-4-3-2-1-0]
Horse2:
[4-4-2-1-1-1-4-9-9-9-8-6-5-4-3-2-5-6]
Horse3:
[2-3-4-5-5-5-5-6-7-8-7-4-5-1-2-4-5-8]
这里的数字代表元素的velocity(速度)。我看过一个特殊的缓动插件,但是没有我想要的缓动。
感谢任何帮助。 谢谢, 内达斯
我在下面提供了一个示例,展示了如何使用 jQuery 的 animate
函数来 "race" 三 "horses" 使用您提供的数据。但是,这是使用 jQuery 提供的标准 "linear" 缓动函数,每个 "horse".
animate
函数
从技术上讲,您可以创建自定义缓动函数来移动马匹,将您的速度数据合并到缓动函数本身。但是,出于以下几个原因,我认为这不是解决问题的好方法:
- 您必须为三匹马中的每匹马编写不同的硬编码缓动函数,因为缓动函数不能被编程为获取输入参数,即速度参数。
- 缓动函数不能存储在数组中,因此您不能调用 myEasingFunction[0]、myEasingFunction[1] 等,但必须使用单独的函数,例如myEasingFunction0、myEasingFunction1 等。这不是很灵活。
- 因为你只想要一匹马 "win",你将不得不在 (1) 之间做出一个丑陋的选择,让你的三个自定义缓动函数中的两个不达到总数的 100% "race" 距离,或者 (2) 必须分别为每匹马提供不同的最终距离,这会破坏创建自定义缓动函数的目的,即必须将某种形式的数据放在两个不同的地方。
无论如何,如果您想了解有关创建自定义缓动函数的信息,请查看 this other Stack Overflow answer。
var horseSpeeds = [
[0, 1, 3, 4, 5, 4, 4, 5, 3, 2, 8, 9, 8, 4, 3, 2, 1, 0],
[4, 4, 2, 1, 1, 1, 4, 9, 9, 9, 8, 6, 5, 4, 3, 2, 5, 6],
[2, 3, 4, 5, 5, 5, 5, 6, 7, 8, 7, 4, 5, 1, 2, 4, 5, 8]
];
var $horses = $("div");
var raceStepNum = 0;
var dist = [0, 0, 0];
var moveHorses = function moveHorses() {
$horses.each(function(horseNum, horse) {
dist[horseNum] += (horseSpeeds[horseNum][raceStepNum]) * 4;
$(horse).animate({
marginLeft: dist[horseNum]
}, 100, "linear", function() {
if (horseNum === 0) {
raceStepNum += 1;
if (raceStepNum < horseSpeeds[0].length) {
moveHorses();
}
}
});
});
}
$("button#startRace").click(moveHorses);
$("button#resetRace").click(function() {
$("div").css({marginLeft: 0});
dist = [0, 0, 0];
raceStepNum = 0;
});
div {
width: 20px;
height: 20px;
margin-bottom: 10px;
}
#horse0 {
background-color: blue;
}
#horse1 {
background-color: red;
}
#horse2 {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="startRace">Start race</button><button id="resetRace">Reset race</button>
<div id="horse0"></div>
<div id="horse1"></div>
<div id="horse2"></div>