r-util-js/packages/common/src/ui/function.ts

48 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* @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
});
}