48 lines
1.3 KiB
TypeScript
48 lines
1.3 KiB
TypeScript
|
|
/*
|
|||
|
|
* @file: /src/ui/function.ts
|
|||
|
|
* @description: 缓动函数之类的,与框架无关,只做计算
|
|||
|
|
* @author: tsl (randy1924@163.com)
|
|||
|
|
* @date: 2026-03-19 11:50:59
|
|||
|
|
* @lastModified: 2026-03-19 15:51:48
|
|||
|
|
* @lastModifiedBy: tsl (randy1924@163.com)
|
|||
|
|
*/
|
|||
|
|
import { easeOutSine } from "js-easing-functions";
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 缓慢滚动到结束值(使用缓动函数)
|
|||
|
|
* @param start 滚动开始值,px
|
|||
|
|
* @param end 滚动结束值,px
|
|||
|
|
* @param duration 完成动画所需的时间,ms
|
|||
|
|
* @param cb 回调函数,参数为当前值,px
|
|||
|
|
*/
|
|||
|
|
export async function slowlyScroll(
|
|||
|
|
start: number,
|
|||
|
|
end: number,
|
|||
|
|
duration: number,
|
|||
|
|
cb?: (value: number) => void,
|
|||
|
|
): Promise<void> {
|
|||
|
|
return new Promise<void>((resolve) => {
|
|||
|
|
const startTime = Date.now();
|
|||
|
|
const distance = end - start;
|
|||
|
|
|
|||
|
|
const intervalId = setInterval(() => {
|
|||
|
|
const currentTime = Date.now();
|
|||
|
|
const elapsed = currentTime - startTime;
|
|||
|
|
|
|||
|
|
// 使用 easeOutSine 缓动函数
|
|||
|
|
// 参数:已过去时间、初始值、改变量、总持续时间
|
|||
|
|
const currentValue = easeOutSine(elapsed, start, distance, duration);
|
|||
|
|
|
|||
|
|
cb?.(currentValue);
|
|||
|
|
|
|||
|
|
if (elapsed >= duration) {
|
|||
|
|
// 清除定时器
|
|||
|
|
clearInterval(intervalId);
|
|||
|
|
// 确保最后一次调用使用准确的结束值
|
|||
|
|
cb?.(end);
|
|||
|
|
resolve();
|
|||
|
|
}
|
|||
|
|
}, 16); // 约60fps
|
|||
|
|
});
|
|||
|
|
}
|