JavaScript 代码
// JavaScript 动画
const element = document.querySelector('.animated-element')
const duration = 2000
function easeBezier(t, p1x, p1y, p2x, p2y) {
const cx = 3 * p1x
const bx = 3 * (p2x - p1x) - cx
const ax = 1 - cx - bx
const cy = 3 * p1y
const by = 3 * (p2y - p1y) - cy
const ay = 1 - cy - by
function sampleCurveX(x) {
return ((ax * x + bx) * x + cx) * x
}
function sampleCurveY(x) {
return ((ay * x + by) * x + cy) * x
}
function solveCurveX(x) {
let t2 = x
for (let i = 0; i < 8; i += 1) {
const x2 = sampleCurveX(t2) - x
if (Math.abs(x2) < 0.001) break
const d2 = (3 * ax * t2 + 2 * bx) * t2 + cx
if (Math.abs(d2) < 0.000001) break
t2 -= x2 / d2
}
return t2
}
return sampleCurveY(solveCurveX(t))
}
function animate() {
const startTime = performance.now()
function frame(currentTime) {
const elapsed = currentTime - startTime
const progress = Math.min(elapsed / duration, 1)
const easedProgress = easeBezier(progress, 0.25, 0.1, 0.25, 1)
element.style.transform = 'translateX(' + (easedProgress * 200) + 'px)'
if (progress < 1) {
requestAnimationFrame(frame)
}
}
requestAnimationFrame(frame)
}
animate()