缓动函数速查表 (easings.net)-cubic-bezier(.06,.44,.94,.7) ✿ cubic-bezier.com
展示了如何使用
easeOutSine
函数来实现一个元素的平滑移动动画。这个demo创建了一个按钮,当点击它时,会使页面上的一个元素向右平滑移动。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>easeOutSine Animation Demo</title>
<style>#animateMe {width: 100px;height: 100px;background-color: steelblue;position: relative;left: 0;}
</style>
</head>
<body><button id="startAnimation">Start Animation</button>
<div id="animateMe"></div><script src="animation.js"></script>
</body>
</html>
animation.js
function easeOutSine(x) {return Math.sin((x * Math.PI) / 2);
}function animate(element, target, duration) {let start = null;const beginningPosition = parseInt(element.style.left, 10) || 0; // 使用parseInt确保得到一个数字const distance = target - beginningPosition;function step(timestamp) {if (!start) start = timestamp;const progress = (timestamp - start) / duration;const easedProgress = easeOutSine(progress > 1 ? 1 : progress); // 确保进度不超过1const newPosition = beginningPosition + distance * easedProgress;element.style.left = newPosition + 'px';if (progress < 1) {requestAnimationFrame(step);}}requestAnimationFrame(step);
}document.getElementById('startAnimation').addEventListener('click', function() {const element = document.getElementById('animateMe');animate(element, 300, 1000); // 将元素在1000毫秒内移动到距离其起始位置300px的地方
});
当用户点击按钮时,
animateMe
元素会在1秒内向右移动300像素。easeOutSine
缓动函数使得动画开始时速度较快,然后逐渐减慢,直至停止。这个简单的demo展示了如何将缓动函数应用于实际的动画效果中,创造出平滑自然的动画过渡效果。