docs: 完成动画文档与编写流程

This commit is contained in:
AncTe committed 2026-11-20 14:23:11 +08:00
1 parent ab09cf1990
commit b194d58c16
76 files changed
+11718 -26

No files matched your search

@@ -0,0 +1,3 @@
import { DelayedPlayback } from './animater-examples';
export default DelayedPlayback;
@@ -0,0 +1,3 @@
import { DelayedTimeline } from './animater-examples';
export default DelayedTimeline;
@@ -0,0 +1,503 @@
import { EndRelation, linear } from '@motajs/animate';
import { Font } from '@motajs/render';
import { useAnimater } from '@motajs/render-vue';
import { defineComponent, nextTick, onMounted, ref } from 'vue';
const LABEL_FONT = new Font('Verdana', 12);
const TRACK_X = 110;
const TRACK_WIDTH = 330;
const TIMELINE_TOP = 112;
const ROW_GAP = 36;
const BUTTON_TOP = 276;
const BLUE = '#58c4dd';
const ORANGE = '#f2b84b';
type ScenarioKind =
| 'sequential'
| 'parallel'
| 'delayed'
| 'relay'
| 'query'
| 'retarget';
type DemoView = 'timeline' | 'playback';
type Animater = NonNullable<ReturnType<typeof useAnimater>>;
interface ISegment {
label: string;
start: number;
end: number;
row: number;
color: string;
}
interface IScenario {
title: string;
hint: string;
total: number;
segments: ISegment[];
}
const SCENARIOS: Record<ScenarioKind, IScenario> = {
sequential: {
title: 'Animater:顺序执行',
hint: 'x 走完,y 才开始',
total: 1150,
segments: [
{ label: 'x1', start: 0, end: 700, row: 0, color: BLUE },
{ label: 'y1', start: 700, end: 1150, row: 1, color: ORANGE }
]
},
parallel: {
title: 'Animater:并行执行',
hint: 'x 与 y 同时开始',
total: 900,
segments: [
{ label: 'x1', start: 0, end: 900, row: 0, color: BLUE },
{ label: 'y1', start: 0, end: 900, row: 1, color: ORANGE }
]
},
delayed: {
title: 'Animater:延迟与重叠',
hint: 'y 在 x 开始 300ms 后启动',
total: 1000,
segments: [
{ label: 'x1', start: 0, end: 1000, row: 0, color: BLUE },
{ label: 'y1', start: 300, end: 900, row: 1, color: ORANGE }
]
},
relay: {
title: 'Animater:组接力',
hint: '组 2 等组 1 全部结束才开始',
total: 1200,
segments: [
{ label: 'x1', start: 0, end: 600, row: 0, color: BLUE },
{ label: 'y1', start: 600, end: 1200, row: 1, color: ORANGE }
]
},
query: {
title: 'Animater:查询与等待',
hint: '读出 y 的步骤,只等待这一条',
total: 300,
segments: [
{ label: 'x1', start: 0, end: 300, row: 0, color: BLUE },
{ label: 'y1', start: 100, end: 300, row: 1, color: ORANGE }
]
},
retarget: {
title: 'Animater:中途改道',
hint: 'x 第 2 段在 700ms 接管第 1 段',
total: 1500,
segments: [
{ label: 'x1', start: 0, end: 700, row: 0, color: BLUE },
{ label: 'x2', start: 700, end: 1200, row: 0, color: BLUE },
{ label: 'y1', start: 0, end: 1500, row: 1, color: ORANGE }
]
}
};
const VIEW_HINTS: Record<ScenarioKind, string> = {
sequential: 'x 结束后,y 才开始。',
parallel: 'x 与 y 在同一组里同时推进。',
delayed: 'y 在 x 开始 300ms 后启动。',
relay: '组 2 等组 1 全部结束才开始。',
query: '读出 y 第 1 段,并只等待它。',
retarget: 'x 第 2 段在 700ms 接管第 1 段。'
};
async function runScenario(
animater: Animater,
kind: ScenarioKind,
x: { value: number },
y: { value: number },
setStatus: (text: string) => void
): Promise<void> {
switch (kind) {
case 'sequential': {
const group = animater
.animate(x)
.curve(linear())
.to(1, 700)
.animate(y)
.after()
.to(1, 450)
.planEnd();
setStatus('x 执行中');
await animater.wait(x, 1, group);
setStatus('x 完成,y 开始');
await animater.wait(y, 1, group);
setStatus('全部完成');
break;
}
case 'parallel': {
const group = animater
.animate(x)
.curve(linear())
.to(1, 900)
.animate(y)
.curve(linear())
.to(1, 900)
.planEnd();
setStatus('x 与 y 同时执行');
await animater.wait(y, 1, group);
setStatus('全部完成');
break;
}
case 'delayed': {
const group = animater
.animate(x)
.curve(linear())
.to(1, 1000)
.when(300)
.animate(y)
.curve(linear())
.to(1, 600)
.planEnd();
setStatus('x 先走,y 延迟 300ms 启动');
await animater.wait(y, 1, group);
setStatus('y 完成,x 仍在走');
await animater.wait(x, 1, group);
setStatus('全部完成');
break;
}
case 'relay': {
const first = animater
.animate(x)
.curve(linear())
.to(1, 600)
.planEnd();
const second = animater
.animate(y)
.curve(linear())
.to(1, 600)
.planEnd();
setStatus('组 1:x 执行中');
await animater.wait(x, 1, first);
setStatus('组 1 完成,组 2 开始');
await animater.wait(y, 1, second);
setStatus('全部完成');
break;
}
case 'query': {
const group = animater
.animate(x)
.curve(linear())
.to(1, 300)
.when(100)
.animate(y)
.curve(linear())
.to(1, 200)
.planEnd();
const yStep = animater.query(y, 1, group);
setStatus(
yStep
? `y 第 1 段:目标 ${yStep.targetValue},时长 ${yStep.time}ms`
: '未查询到 y 第 1 段'
);
await animater.wait(x, 1, group);
setStatus('x 完成');
await animater.wait(y, 1, group);
setStatus('y 完成,只等了指定步骤');
break;
}
case 'retarget': {
const group = animater
.animate(x)
.curve(linear())
.to(1, 1200, EndRelation.Self)
.animate(y)
.curve(linear())
.to(1, 1500)
.whenPlan(x, 1, 700)
.animate(x)
.curve(linear())
.to(0, 500)
.planEnd();
const second = animater.query(x, 2, group);
setStatus(
second
? `x 第 2 段:目标 ${second.targetValue},时长 ${second.time}ms`
: '未查询到 x 第 2 段'
);
await animater.wait(x, 1, group);
setStatus('x 第 1 段在改道时结束');
await animater.wait(x, 2, group);
setStatus('x 第 2 段完成,y 仍在走');
await animater.wait(y, 1, group);
setStatus('全部完成');
break;
}
}
}
function createDemo(kind: ScenarioKind, view: DemoView) {
const scenario = SCENARIOS[kind];
return defineComponent(() => {
const animater = useAnimater()!;
const clock = useAnimater()!;
const x = ref(0);
const y = ref(0);
const phase = ref(0);
const running = ref(false);
const status = ref('等待开始');
const play = async () => {
if (running.value) return;
running.value = true;
x.value = 0;
y.value = 0;
phase.value = 0;
status.value = '准备开始';
clock
.animate(phase)
.curve(linear())
.to(1, scenario.total)
.planEnd();
await runScenario(animater, kind, x, y, text => {
status.value = text;
});
running.value = false;
};
onMounted(() => {
nextTick(() => {
void play();
});
});
const renderTimeline = () => {
const playhead = TRACK_X + phase.value * TRACK_WIDTH;
const elapsed = Math.round(phase.value * scenario.total);
return (
<>
<text
loc={[24, TIMELINE_TOP - 14]}
text="x"
fillStyle="#cfe0ff"
/>
<text
loc={[24, TIMELINE_TOP + ROW_GAP - 14]}
text="y"
fillStyle="#cfe0ff"
/>
{[0, 1].map(row => (
<g-rect
key={row}
loc={[
TRACK_X,
TIMELINE_TOP + row * ROW_GAP,
TRACK_WIDTH,
16
]}
fillStyle="#1c2633"
/>
))}
{scenario.segments.map(segment => {
const left =
TRACK_X +
(segment.start / scenario.total) * TRACK_WIDTH;
const width =
((segment.end - segment.start) / scenario.total) *
TRACK_WIDTH;
const top = TIMELINE_TOP + segment.row * ROW_GAP;
return (
<container
key={segment.label}
loc={[left, top, width, 16]}
>
<g-rectr
loc={[0, 0, width, 16]}
circle={[4]}
fillStyle={segment.color}
/>
<text
loc={[5, 2]}
text={segment.label}
font={LABEL_FONT}
fillStyle="#0e141b"
/>
</container>
);
})}
<g-rect
loc={[playhead - 1, TIMELINE_TOP - 8, 2, ROW_GAP + 32]}
fillStyle="#e8f0ff"
/>
<g-circle
circle={[playhead, TIMELINE_TOP - 8, 4]}
fillStyle="#e8f0ff"
/>
<text
loc={[456, TIMELINE_TOP - 18]}
anc={[1, 0]}
text={`${elapsed} ms`}
font={LABEL_FONT}
fillStyle="#8fb6ff"
/>
<text
loc={[24, 214]}
text={`x ${x.value.toFixed(2)} y ${y.value.toFixed(2)}`}
font={LABEL_FONT}
fillStyle="#cfe0ff"
/>
<text
loc={[24, 236]}
text="色块是步骤段,竖线是播放头。"
font={LABEL_FONT}
fillStyle="#8b98a8"
/>
<text
loc={[24, 254]}
text="播放头由另一个真实执行器推进。"
font={LABEL_FONT}
fillStyle="#8b98a8"
/>
</>
);
};
const renderPlayback = () => {
const retargetX = TRACK_X + (700 / scenario.total) * TRACK_WIDTH;
return (
<>
<text loc={[24, 96]} text="x" fillStyle="#cfe0ff" />
<g-rect
loc={[TRACK_X, 104, TRACK_WIDTH, 8]}
fillStyle="#26364d"
/>
<g-circle
circle={[TRACK_X + x.value * TRACK_WIDTH, 108, 7]}
fillStyle={BLUE}
/>
<text
loc={[456, 96]}
anc={[1, 0]}
text={x.value.toFixed(2)}
font={LABEL_FONT}
fillStyle="#8fb6ff"
/>
<text loc={[24, 146]} text="y" fillStyle="#cfe0ff" />
<g-rect
loc={[TRACK_X, 154, TRACK_WIDTH, 8]}
fillStyle="#26364d"
/>
<g-circle
circle={[TRACK_X + y.value * TRACK_WIDTH, 158, 7]}
fillStyle={ORANGE}
/>
<text
loc={[456, 146]}
anc={[1, 0]}
text={y.value.toFixed(2)}
font={LABEL_FONT}
fillStyle="#f2b84b"
/>
{kind === 'retarget' && (
<>
<g-rect
loc={[retargetX - 1, 96, 2, 24]}
fillStyle="#e8f0ff"
/>
<text
loc={[retargetX - 16, 82]}
text="改道"
font={LABEL_FONT}
fillStyle="#e8f0ff"
/>
</>
)}
<text
loc={[24, 202]}
text={status.value}
font={LABEL_FONT}
fillStyle="#7ee787"
/>
<text
loc={[24, 226]}
text={VIEW_HINTS[kind]}
font={LABEL_FONT}
fillStyle="#8b98a8"
/>
</>
);
};
return () => (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text
loc={[24, 14]}
text={scenario.title}
fillStyle="#e8f0ff"
/>
<text loc={[24, 36]} text={scenario.hint} fillStyle="#8b98a8" />
<text
loc={[24, 56]}
text={view === 'timeline' ? '时间轴视图' : '播放视图'}
font={LABEL_FONT}
fillStyle="#8b98a8"
/>
{view === 'timeline' ? renderTimeline() : renderPlayback()}
<container
loc={[24, BUTTON_TOP, 100, 30]}
cursor="pointer"
onClick={() => {
void play();
}}
>
<g-rectr
loc={[0, 0, 100, 30]}
circle={[8]}
fillStyle={running.value ? '#33465f' : '#2f6fed'}
/>
<text
loc={[50, 15]}
anc={[0.5, 0.5]}
text={running.value ? '播放中' : '重播'}
font={LABEL_FONT}
fillStyle="#e8f0ff"
/>
</container>
<text
loc={[136, BUTTON_TOP + 8]}
text={running.value ? '真实执行器正在推进' : '点击重播'}
font={LABEL_FONT}
fillStyle="#8b98a8"
/>
</container>
);
});
}
export const SequentialTimeline = createDemo('sequential', 'timeline');
export const SequentialPlayback = createDemo('sequential', 'playback');
export const ParallelTimeline = createDemo('parallel', 'timeline');
export const ParallelPlayback = createDemo('parallel', 'playback');
export const DelayedTimeline = createDemo('delayed', 'timeline');
export const DelayedPlayback = createDemo('delayed', 'playback');
export const RelayTimeline = createDemo('relay', 'timeline');
export const RelayPlayback = createDemo('relay', 'playback');
export const QueryTimeline = createDemo('query', 'timeline');
export const QueryPlayback = createDemo('query', 'playback');
export const RetargetTimeline = createDemo('retarget', 'timeline');
export const RetargetPlayback = createDemo('retarget', 'playback');
@@ -0,0 +1,3 @@
import { ParallelPlayback } from './animater-examples';
export default ParallelPlayback;
@@ -0,0 +1,3 @@
import { ParallelTimeline } from './animater-examples';
export default ParallelTimeline;
@@ -0,0 +1,3 @@
import { QueryPlayback } from './animater-examples';
export default QueryPlayback;
@@ -0,0 +1,3 @@
import { QueryTimeline } from './animater-examples';
export default QueryTimeline;
@@ -0,0 +1,3 @@
import { RelayPlayback } from './animater-examples';
export default RelayPlayback;
@@ -0,0 +1,3 @@
import { RelayTimeline } from './animater-examples';
export default RelayTimeline;
@@ -0,0 +1,3 @@
import { RetargetPlayback } from './animater-examples';
export default RetargetPlayback;
@@ -0,0 +1,3 @@
import { RetargetTimeline } from './animater-examples';
export default RetargetTimeline;
@@ -0,0 +1,3 @@
import { SequentialPlayback } from './animater-examples';
export default SequentialPlayback;
@@ -0,0 +1,3 @@
import { SequentialTimeline } from './animater-examples';
export default SequentialTimeline;
@@ -0,0 +1,241 @@
import { linear } from '@motajs/animate';
import { Font } from '@motajs/render';
import { useAnimater } from '@motajs/render-vue';
import { defineComponent, nextTick, onMounted, ref } from 'vue';
const LABEL_FONT = new Font('Verdana', 12);
const TOTAL = 1400;
const A1_TIME = 800;
const A2_DELAY = 200;
const A2_TIME = 400;
const B1_DELAY = 200;
const B1_TIME = 500;
const B2_DELAY = 150;
const B2_TIME = 300;
const TRACK_X = 70;
const TRACK_WIDTH = 350;
const TIMELINE_TOP = 164;
interface ITimelineSegment {
label: string;
start: number;
end: number;
row: number;
color: string;
}
const SEGMENTS: ITimelineSegment[] = [
{ label: 'A1', start: 0, end: A1_TIME, row: 0, color: '#58c4dd' },
{
label: 'A2',
start: A1_TIME + A2_DELAY,
end: A1_TIME + A2_DELAY + A2_TIME,
row: 0,
color: '#58c4dd'
},
{
label: 'B1',
start: B1_DELAY,
end: B1_DELAY + B1_TIME,
row: 1,
color: '#f2b84b'
},
{
label: 'B2',
start: B1_DELAY + B1_TIME + B2_DELAY,
end: B1_DELAY + B1_TIME + B2_DELAY + B2_TIME,
row: 1,
color: '#f2b84b'
}
];
// 时间线演示:两个动画对象由同一个 Animater 推进,播放头本身也是一条计划
export default defineComponent(() => {
const animater = useAnimater()!;
const left = ref(0);
const right = ref(0);
const phase = ref(0);
const running = ref(false);
const play = async () => {
if (running.value) return;
running.value = true;
left.value = 0;
right.value = 0;
phase.value = 0;
const group = animater
.animate(phase)
.curve(linear())
.to(1, TOTAL)
.animate(left)
.when(0)
.to(1, A1_TIME)
.animate(right)
.when(B1_DELAY)
.to(1, B1_TIME)
.animate(right)
.after(B2_DELAY)
.to(0, B2_TIME)
.animate(left)
.afterPlan(left, 1, A2_DELAY)
.to(0, A2_TIME)
.planEnd();
await animater.wait(phase, 1, group);
running.value = false;
};
onMounted(() => {
nextTick(() => {
void play();
});
});
return () => {
const playhead = TRACK_X + phase.value * TRACK_WIDTH;
const elapsed = Math.round(phase.value * TOTAL);
return (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text
loc={[24, 16]}
text="Animater:计划组时间线"
fillStyle="#e8f0ff"
/>
<text
loc={[24, 38]}
text="两条轨迹由同一个执行器推进,色块是计划段"
fillStyle="#8b98a8"
/>
<text loc={[24, 64]} text="对象 A" fillStyle="#cfe0ff" />
<text
loc={[456, 64]}
anc={[1, 0]}
text={`value ${left.value.toFixed(2)}`}
font={LABEL_FONT}
fillStyle="#8fb6ff"
/>
<g-rect
loc={[TRACK_X, 81, TRACK_WIDTH, 2]}
fillStyle="#26364d"
/>
<g-circle
circle={[TRACK_X + left.value * TRACK_WIDTH, 82, 7]}
fillStyle="#58c4dd"
/>
<text loc={[24, 100]} text="对象 B" fillStyle="#cfe0ff" />
<text
loc={[456, 100]}
anc={[1, 0]}
text={`value ${right.value.toFixed(2)}`}
font={LABEL_FONT}
fillStyle="#8fb6ff"
/>
<g-rect
loc={[TRACK_X, 117, TRACK_WIDTH, 2]}
fillStyle="#26364d"
/>
<g-circle
circle={[TRACK_X + right.value * TRACK_WIDTH, 118, 7]}
fillStyle="#f2b84b"
/>
<text loc={[24, 142]} text="计划组 1" fillStyle="#cfe0ff" />
<text
loc={[456, 142]}
anc={[1, 0]}
text={`${elapsed} ms`}
font={LABEL_FONT}
fillStyle="#8fb6ff"
/>
<g-rect
loc={[TRACK_X, TIMELINE_TOP, TRACK_WIDTH, 16]}
fillStyle="#1c2633"
/>
<g-rect
loc={[TRACK_X, TIMELINE_TOP + 26, TRACK_WIDTH, 16]}
fillStyle="#1c2633"
/>
<text loc={[24, TIMELINE_TOP]} text="A" fillStyle="#e8f0ff" />
<text
loc={[24, TIMELINE_TOP + 26]}
text="B"
fillStyle="#e8f0ff"
/>
{SEGMENTS.map(segment => {
const x = TRACK_X + (segment.start / TOTAL) * TRACK_WIDTH;
const width =
((segment.end - segment.start) / TOTAL) * TRACK_WIDTH;
const y = TIMELINE_TOP + segment.row * 26;
return (
<container key={segment.label} loc={[x, y, width, 16]}>
<g-rectr
loc={[0, 0, width, 16]}
circle={[4]}
fillStyle={segment.color}
/>
<text
loc={[5, 2]}
text={segment.label}
font={LABEL_FONT}
fillStyle="#0e141b"
/>
</container>
);
})}
<g-rect loc={[playhead - 1, 156, 2, 60]} fillStyle="#e8f0ff" />
<g-circle circle={[playhead, 156, 4]} fillStyle="#e8f0ff" />
<text
loc={[24, 224]}
text="A1 0–800ms;A2 在 A1 结束后 200ms 开始"
font={LABEL_FONT}
fillStyle="#8b98a8"
/>
<text
loc={[24, 242]}
text="B1 在 A1 开始后 200ms 开始;B2 在 B1 结束后 150ms 开始"
font={LABEL_FONT}
fillStyle="#8b98a8"
/>
<container
loc={[70, 268, 100, 30]}
cursor="pointer"
onClick={() => {
void play();
}}
>
<g-rectr
loc={[0, 0, 100, 30]}
circle={[8]}
fillStyle={running.value ? '#33465f' : '#2f6fed'}
/>
<text
loc={[50, 15]}
anc={[0.5, 0.5]}
text={running.value ? '播放中' : '重播'}
font={LABEL_FONT}
fillStyle="#e8f0ff"
/>
</container>
<text
loc={[184, 276]}
text={running.value ? '播放头正在推进' : '点击重播时间线'}
font={LABEL_FONT}
fillStyle="#8b98a8"
/>
</container>
);
};
});
@@ -0,0 +1,123 @@
import { CurveMode, linear, sin } from '@motajs/animate';
import { transitioned } from '@motajs/render-vue';
import { defineComponent, ref } from 'vue';
// 数值渐变:alpha、位置与进度条
export default defineComponent(() => {
const alpha = transitioned(0.25, 600, sin(CurveMode.EaseOut))!;
const slide = transitioned(0, 600, sin(CurveMode.EaseOut))!;
const bar = transitioned(0.3, 600, sin(CurveMode.EaseOut))!;
const high = ref(false);
const smooth = ref(true);
const slow = ref(false);
const toggle = () => {
high.value = !high.value;
alpha.set(high.value ? 1 : 0.25);
slide.set(high.value ? 1 : 0);
bar.set(high.value ? 1 : 0.3);
};
const toggleCurve = () => {
smooth.value = !smooth.value;
const curve = smooth.value ? sin() : linear();
alpha.mode(curve);
slide.mode(curve);
bar.mode(curve);
toggle();
};
const toggleTime = () => {
slow.value = !slow.value;
const time = slow.value ? 1200 : 600;
alpha.setTime(time);
slide.setTime(time);
bar.setTime(time);
toggle();
};
return () => (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text
loc={[24, 16]}
text="transitioned:数值渐变"
fillStyle="#e8f0ff"
/>
<text
loc={[24, 40]}
text="alpha 与位置都读 ref.value"
fillStyle="#8b98a8"
/>
<text loc={[40, 72]} text="alpha" fillStyle="#cfe0ff" />
<g-rect
loc={[40, 92, 120, 88]}
fillStyle="#2f6fed"
alpha={alpha.ref.value}
/>
<text
loc={[40, 190]}
text={alpha.ref.value.toFixed(2)}
fillStyle="#8fb6ff"
/>
<text loc={[200, 72]} text="position" fillStyle="#cfe0ff" />
<g-rect loc={[200, 136, 200, 8]} fillStyle="#26364d" />
<g-circle
circle={[204 + slide.ref.value * 192, 140, 12]}
fillStyle="#f2b84b"
/>
<text
loc={[200, 190]}
text={slide.ref.value.toFixed(2)}
fillStyle="#8fb6ff"
/>
<text loc={[40, 214]} text="progress" fillStyle="#cfe0ff" />
<g-rect loc={[40, 234, 280, 12]} fillStyle="#26364d" />
<g-rect
loc={[40, 234, 280 * bar.ref.value, 12]}
fillStyle="#7ee787"
/>
<text
loc={[330, 230]}
text={`${Math.round(bar.ref.value * 100)}%`}
fillStyle="#8fb6ff"
/>
<container loc={[40, 264, 96, 32]} onClick={toggle}>
<g-rectr
loc={[0, 0, 96, 32]}
circle={[8]}
fillStyle="#2f6fed"
/>
<text loc={[12, 8]} text="切换" fillStyle="#ffffff" />
</container>
<container loc={[144, 264, 96, 32]} onClick={toggleCurve}>
<g-rectr
loc={[0, 0, 96, 32]}
circle={[8]}
fillStyle="#33465f"
/>
<text
loc={[12, 8]}
text={smooth.value ? '缓动' : '线性'}
fillStyle="#e8f0ff"
/>
</container>
<container loc={[248, 264, 96, 32]} onClick={toggleTime}>
<g-rectr
loc={[0, 0, 96, 32]}
circle={[8]}
fillStyle="#33465f"
/>
<text
loc={[12, 8]}
text={slow.value ? '慢速' : '快速'}
fillStyle="#e8f0ff"
/>
</container>
</container>
);
});
@@ -0,0 +1,61 @@
import { CurveMode, sin } from '@motajs/animate';
import { transitionedColor } from '@motajs/render-vue';
import { defineComponent, ref } from 'vue';
// 颜色渐变:填充色与描边色
export default defineComponent(() => {
const fill = transitionedColor('#2f6fed', 600, sin(CurveMode.EaseOut))!;
const stroke = transitionedColor(
'rgba(242, 184, 75, 0.9)',
600,
sin(CurveMode.EaseOut)
)!;
const warm = ref(true);
const toggle = () => {
warm.value = !warm.value;
fill.set(warm.value ? '#2f6fed' : '#f2b84b');
stroke.set(warm.value ? 'rgba(242, 184, 75, 0.9)' : '#7ee787');
};
return () => (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text
loc={[24, 16]}
text="transitionedColor:颜色渐变"
fillStyle="#e8f0ff"
/>
<text
loc={[24, 40]}
text="填充与描边都读 ref.value"
fillStyle="#8b98a8"
/>
<text loc={[40, 64]} text="fillStyle" fillStyle="#cfe0ff" />
<g-rectr
loc={[40, 88, 180, 140]}
circle={[16]}
fillStyle={fill.ref.value}
/>
<text loc={[60, 144]} text="color" fillStyle="#ffffff" />
<text loc={[280, 64]} text="strokeStyle" fillStyle="#cfe0ff" />
<g-circle
circle={[320, 158, 56]}
stroke
strokeStyle={stroke.ref.value}
lineWidth={10}
/>
<container loc={[40, 264, 120, 32]} onClick={toggle}>
<g-rectr
loc={[0, 0, 120, 32]}
circle={[8]}
fillStyle="#33465f"
/>
<text loc={[12, 8]} text="切换颜色" fillStyle="#e8f0ff" />
</container>
</container>
);
});
@@ -0,0 +1,22 @@
import { addCurve, constant, sin } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveCalcLab from './animation-curve-calc';
const SOURCE_1 = sin();
const SOURCE_2 = constant(0.2);
const RESULT = addCurve(SOURCE_1, SOURCE_2);
// 相加:两条来源曲线的逐点和
export default defineComponent(() => {
return () => (
<CurveCalcLab
title="addCurve"
subtitle="结果 = f(x) + g(x)"
curves={[
{ label: 'sin()', color: '#2f6fed', curve: SOURCE_1 },
{ label: 'constant(0.2)', color: '#f2b84b', curve: SOURCE_2 },
{ label: 'addCurve', color: '#7ee787', curve: RESULT }
]}
/>
);
});
@@ -0,0 +1,22 @@
import { compositeCurve, pow, sin } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveCalcLab from './animation-curve-calc';
const OUTER = sin();
const INNER = pow(2);
const RESULT = compositeCurve(OUTER, INNER);
// 复合:外层曲线接收内层曲线的输出
export default defineComponent(() => {
return () => (
<CurveCalcLab
title="compositeCurve"
subtitle="结果 = 外层(内层(p))"
curves={[
{ label: 'sin()', color: '#2f6fed', curve: OUTER },
{ label: 'pow(2)', color: '#f2b84b', curve: INNER },
{ label: 'compositeCurve', color: '#7ee787', curve: RESULT }
]}
/>
);
});
@@ -0,0 +1,22 @@
import { constant, divCurve, linear } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveCalcLab from './animation-curve-calc';
const SOURCE_1 = linear();
const SOURCE_2 = constant(0.5);
const RESULT = divCurve(SOURCE_1, SOURCE_2);
// 相除:两条来源曲线的逐点商,分母取常数避免过零
export default defineComponent(() => {
return () => (
<CurveCalcLab
title="divCurve"
subtitle="结果 = f(x) / g(x)"
curves={[
{ label: 'linear()', color: '#2f6fed', curve: SOURCE_1 },
{ label: 'constant(0.5)', color: '#f2b84b', curve: SOURCE_2 },
{ label: 'divCurve', color: '#7ee787', curve: RESULT }
]}
/>
);
});
@@ -0,0 +1,20 @@
import { moveCurve, sin } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveCalcLab from './animation-curve-calc';
const SOURCE = sin();
const RESULT = moveCurve(SOURCE, 0.2);
// 平移:在来源曲线上加一个纵向偏移
export default defineComponent(() => {
return () => (
<CurveCalcLab
title="moveCurve"
subtitle="结果 = f(x) + move"
curves={[
{ label: 'sin()', color: '#2f6fed', curve: SOURCE },
{ label: 'moveCurve', color: '#7ee787', curve: RESULT }
]}
/>
);
});
@@ -0,0 +1,22 @@
import { linear, mulCurve, sin } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveCalcLab from './animation-curve-calc';
const SOURCE_1 = sin();
const SOURCE_2 = linear();
const RESULT = mulCurve(SOURCE_1, SOURCE_2);
// 相乘:两条来源曲线的逐点积
export default defineComponent(() => {
return () => (
<CurveCalcLab
title="mulCurve"
subtitle="结果 = f(x) · g(x)"
curves={[
{ label: 'sin()', color: '#2f6fed', curve: SOURCE_1 },
{ label: 'linear()', color: '#f2b84b', curve: SOURCE_2 },
{ label: 'mulCurve', color: '#7ee787', curve: RESULT }
]}
/>
);
});
@@ -0,0 +1,20 @@
import { moveCurve, normalize, scaleCurve, sin } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveCalcLab from './animation-curve-calc';
const SOURCE = moveCurve(scaleCurve(sin(), 0.6), 0.2);
const RESULT = normalize(SOURCE);
// 归一化:把来源曲线的两端对齐到 0 与 1
export default defineComponent(() => {
return () => (
<CurveCalcLab
title="normalize"
subtitle="结果按 curve(0) 与 curve(1) 归一化"
curves={[
{ label: '0.2 + 0.6·sin()', color: '#2f6fed', curve: SOURCE },
{ label: 'normalize', color: '#7ee787', curve: RESULT }
]}
/>
);
});
@@ -0,0 +1,20 @@
import { oppositeCurve, sin } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveCalcLab from './animation-curve-calc';
const SOURCE = sin();
const RESULT = oppositeCurve(SOURCE, 1);
// 取反:以 move 为基准翻转来源曲线
export default defineComponent(() => {
return () => (
<CurveCalcLab
title="oppositeCurve"
subtitle="结果 = move - f(x)"
curves={[
{ label: 'sin()', color: '#2f6fed', curve: SOURCE },
{ label: 'oppositeCurve', color: '#7ee787', curve: RESULT }
]}
/>
);
});
@@ -0,0 +1,22 @@
import { constant, linear, powCurve } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveCalcLab from './animation-curve-calc';
const SOURCE_1 = linear();
const SOURCE_2 = constant(2);
const RESULT = powCurve(SOURCE_1, SOURCE_2);
// 取幂:第一条曲线为底,第二条曲线为指数
export default defineComponent(() => {
return () => (
<CurveCalcLab
title="powCurve"
subtitle="结果 = f(x) ^ g(x)"
curves={[
{ label: 'linear()', color: '#2f6fed', curve: SOURCE_1 },
{ label: 'constant(2)', color: '#f2b84b', curve: SOURCE_2 },
{ label: 'powCurve', color: '#7ee787', curve: RESULT }
]}
/>
);
});
@@ -0,0 +1,25 @@
import {
linear,
moveCurve,
reciprocalCurve,
scaleCurve
} from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveCalcLab from './animation-curve-calc';
const SOURCE = moveCurve(scaleCurve(linear(), 0.5), 0.5);
const RESULT = reciprocalCurve(SOURCE, 0.5);
// 倒数:来源曲线取值在 0.5 到 1,避免分母过零
export default defineComponent(() => {
return () => (
<CurveCalcLab
title="reciprocalCurve"
subtitle="结果 = scale / f(x)"
curves={[
{ label: '0.5 + 0.5p', color: '#2f6fed', curve: SOURCE },
{ label: 'reciprocalCurve', color: '#7ee787', curve: RESULT }
]}
/>
);
});
@@ -0,0 +1,20 @@
import { scaleCurve, sin } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveCalcLab from './animation-curve-calc';
const SOURCE = sin();
const RESULT = scaleCurve(SOURCE, 0.5);
// 缩放:纵向缩小来源曲线
export default defineComponent(() => {
return () => (
<CurveCalcLab
title="scaleCurve"
subtitle="结果 = f(x) · scale"
curves={[
{ label: 'sin()', color: '#2f6fed', curve: SOURCE },
{ label: 'scaleCurve', color: '#7ee787', curve: RESULT }
]}
/>
);
});
@@ -0,0 +1,27 @@
import { linear, sequenceCurve, sin } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveCalcLab from './animation-curve-calc';
const SEGMENT_1 = linear();
const SEGMENT_2 = sin();
const RESULT = sequenceCurve(
[SEGMENT_1, SEGMENT_2],
[0.5, 0.5],
[1, 1],
[0, 0]
);
// 拼接:两条来源段按各占一半时长合成一条曲线
export default defineComponent(() => {
return () => (
<CurveCalcLab
title="sequenceCurve"
subtitle="来源段按 0.5 / 0.5 的时长拼接"
curves={[
{ label: 'linear()', color: '#2f6fed', curve: SEGMENT_1 },
{ label: 'sin()', color: '#f2b84b', curve: SEGMENT_2 },
{ label: 'sequenceCurve', color: '#7ee787', curve: RESULT }
]}
/>
);
});
@@ -0,0 +1,22 @@
import { constant, linear, subCurve } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveCalcLab from './animation-curve-calc';
const SOURCE_1 = constant(0.8);
const SOURCE_2 = linear();
const RESULT = subCurve(SOURCE_1, SOURCE_2);
// 相减:两条来源曲线的逐点差
export default defineComponent(() => {
return () => (
<CurveCalcLab
title="subCurve"
subtitle="结果 = f(x) - g(x)"
curves={[
{ label: 'constant(0.8)', color: '#2f6fed', curve: SOURCE_1 },
{ label: 'linear()', color: '#f2b84b', curve: SOURCE_2 },
{ label: 'subCurve', color: '#7ee787', curve: RESULT }
]}
/>
);
});
@@ -0,0 +1,99 @@
import { Font } from '@motajs/render';
import { SetupComponentOptions } from '@motajs/system';
import { defineComponent } from 'vue';
import { createCurveRender, type CurveEntry } from './animation-curve-plot';
const LABEL_FONT = new Font('Verdana', 12);
export interface ICurveCalcLabProps {
/** 计算函数名称,显示在标题位置 */
title: string;
/** 来源与结果的简短说明 */
subtitle: string;
/** 来源曲线与结果曲线;通常前两项是来源,最后一项是结果 */
curves: CurveEntry[];
}
const curveCalcLabProps = {
props: ['title', 'subtitle', 'curves']
} satisfies SetupComponentOptions<ICurveCalcLabProps>;
const RANGE_SAMPLES = 120;
// 按来源与结果曲线的实际采样计算显示范围,避免把越界输出截断
function getDisplayRange(curves: CurveEntry[]): {
min: number;
max: number;
} {
let min = Infinity;
let max = -Infinity;
for (const entry of curves) {
for (let i = 0; i <= RANGE_SAMPLES; i++) {
const value = entry.curve(i / RANGE_SAMPLES);
if (!Number.isFinite(value)) continue;
min = Math.min(min, value);
max = Math.max(max, value);
}
}
if (!Number.isFinite(min) || !Number.isFinite(max)) {
return { min: 0, max: 1 };
}
// 0 是进度映射的基准,显示范围需要包含它
min = Math.min(min, 0);
max = Math.max(max, 0);
const span = max - min;
const padding = span > 0 ? span * 0.1 : 0.1;
return { min: min - padding, max: max + padding };
}
// 曲线计算实验台:标题、说明、来源与结果曲线图
const CurveCalcLab = defineComponent<ICurveCalcLabProps>((props, { slots }) => {
return () => {
const render = createCurveRender(
props.curves,
getDisplayRange(props.curves)
);
return (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text loc={[24, 16]} text={props.title} fillStyle="#e8f0ff" />
<text
loc={[24, 38]}
text={props.subtitle}
fillStyle="#8b98a8"
/>
<custom loc={[36, 64, 408, 190]} render={render} />
{props.curves.map((entry, index) => (
<container
key={entry.label}
loc={[40 + index * 140, 266, 132, 20]}
>
<g-line
line={[0, 10, 18, 10]}
strokeStyle={entry.color}
lineWidth={4}
/>
<text
loc={[24, 4]}
text={entry.label}
font={LABEL_FONT}
fillStyle="#cfe0ff"
/>
</container>
))}
{slots.default?.()}
</container>
);
};
}, curveCalcLabProps);
export default CurveCalcLab;
@@ -0,0 +1,30 @@
import { constant } from '@motajs/animate';
import { defineComponent, ref } from 'vue';
import { Slider } from '../../../../../packages-user/client-base/src/components/slider';
import CurveLab from './animation-curve-lab';
const VALUE_MIN = 0;
const VALUE_MAX = 1;
// 常数曲线:输出始终等于 k
export default defineComponent(() => {
const k = ref(0.5);
return () => (
<CurveLab
title="constant(k)"
subtitle="常数曲线:输出始终等于 k(示例 k 取 0 到 1)"
curve={() => constant(k.value)}
bindings={[k.value]}
>
<text loc={[24, 4]} text="常数值 k" fillStyle="#cfe0ff" />
<Slider
loc={[112, 0, 336, 24]}
v-model:value={k.value}
min={VALUE_MIN}
max={VALUE_MAX}
step={0.05}
/>
</CurveLab>
);
});
@@ -0,0 +1,31 @@
import { cosh } from '@motajs/animate';
import { defineComponent, ref } from 'vue';
import { Slider } from '../../../../../packages-user/client-base/src/components/slider';
import CurveLab from './animation-curve-lab';
const K_MIN = 0.5;
const K_MAX = 4;
// 双曲余弦曲线:调整比例参数 k,切换四种 CurveMode
export default defineComponent(() => {
const k = ref(2);
return () => (
<CurveLab
title="cosh(k = 2, mode?)"
subtitle="双曲余弦曲线:调整 k 与模式"
curve={mode => cosh(k.value, mode)}
bindings={[k.value]}
supportsMode
>
<text loc={[24, 4]} text="比例参数 k" fillStyle="#cfe0ff" />
<Slider
loc={[112, 0, 336, 24]}
v-model:value={k.value}
min={K_MIN}
max={K_MAX}
step={0.1}
/>
</CurveLab>
);
});
@@ -0,0 +1,131 @@
import { CurveMode, type ExcitationCurve } from '@motajs/animate';
import { Font } from '@motajs/render';
import { SetupComponentOptions } from '@motajs/system';
import { defineComponent, ref } from 'vue';
import { createCurveRender } from './animation-curve-plot';
const LABEL_FONT = new Font('Verdana', 12);
const MODE_ITEMS: { mode: CurveMode; label: string; hint: string }[] = [
{ mode: CurveMode.EaseIn, label: 'EaseIn', hint: '缓进快出' },
{ mode: CurveMode.EaseOut, label: 'EaseOut', hint: '快进缓出' },
{ mode: CurveMode.EaseInOut, label: 'EaseInOut', hint: '缓进缓出,中间快' },
{
mode: CurveMode.EaseCenter,
label: 'EaseCenter',
hint: '快进快出,中间缓'
}
];
export interface ICurveLabProps {
/** 曲线名称,显示在标题位置 */
title: string;
/** 曲线说明,显示在标题下方 */
subtitle: string;
/** 按当前模式生成要绘制的曲线 */
curve: (mode: CurveMode) => ExcitationCurve;
/** 曲线依赖的响应式值;变化时重绘 */
bindings: unknown[];
/** 是否显示四种曲线模式的按钮 */
supportsMode?: boolean;
/** 没有控件时显示的说明 */
note?: string;
}
const curveLabProps = {
props: ['title', 'subtitle', 'curve', 'bindings', 'supportsMode', 'note']
} satisfies SetupComponentOptions<ICurveLabProps>;
// 曲线实验台:标题、说明、曲线图,以及可选的模式按钮与参数控件
const CurveLab = defineComponent<ICurveLabProps>((props, { slots }) => {
const mode = ref<CurveMode>(CurveMode.EaseIn);
return () => {
const supportsMode = props.supportsMode ?? false;
const currentMode =
MODE_ITEMS.find(item => item.mode === mode.value) ?? MODE_ITEMS[0];
const hasBody = Boolean(slots.default) || Boolean(props.note);
const modeTop = hasBody ? 258 : 272;
const bodyTop = supportsMode ? 292 : 268;
const render = createCurveRender([
{
label: props.title,
color: '#7ee787',
curve: props.curve(mode.value)
}
]);
return (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text loc={[24, 16]} text={props.title} fillStyle="#e8f0ff" />
<text
loc={[24, 38]}
text={props.subtitle}
fillStyle="#8b98a8"
/>
{supportsMode && (
<text
loc={[456, 16]}
anc={[1, 0]}
text={currentMode.hint}
font={LABEL_FONT}
fillStyle="#8b98a8"
/>
)}
<custom
loc={[36, 64, 408, 190]}
bindings={[...props.bindings, mode.value]}
render={render}
/>
{supportsMode &&
MODE_ITEMS.map((item, index) => {
const active = item.mode === mode.value;
return (
<container
key={item.label}
loc={[28 + index * 108, modeTop, 100, 26]}
cursor="pointer"
onClick={() => {
mode.value = item.mode;
}}
>
<g-rectr
loc={[0, 0, 100, 26]}
circle={[8]}
fillStyle={active ? '#2f6fed' : '#26364d'}
/>
<text
loc={[50, 13]}
anc={[0.5, 0.5]}
text={item.label}
font={LABEL_FONT}
fillStyle={active ? '#ffffff' : '#cfe0ff'}
noevent
/>
</container>
);
})}
{hasBody && (
<container loc={[0, bodyTop, 480, 26]}>
{slots.default?.()}
{!slots.default && props.note && (
<text
loc={[24, 4]}
text={props.note}
fillStyle="#8b98a8"
/>
)}
</container>
)}
</container>
);
};
}, curveLabProps);
export default CurveLab;
@@ -0,0 +1,16 @@
import { linear } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveLab from './animation-curve-lab';
// 线性曲线:没有参数,输出始终等于 x
export default defineComponent(() => {
return () => (
<CurveLab
title="linear()"
subtitle="线性曲线:输出等于 x"
curve={() => linear()}
bindings={[]}
note="无参数"
/>
);
});
@@ -0,0 +1,16 @@
import { sin } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveLab from './animation-curve-lab';
// 曲线模式:同一条正弦曲线在四种 CurveMode 之间切换
export default defineComponent(() => {
return () => (
<CurveLab
title="sin()"
subtitle="同一条正弦曲线在四种模式之间切换"
curve={mode => sin(mode)}
bindings={[]}
supportsMode
/>
);
});
@@ -0,0 +1,113 @@
import type { ExcitationCurve } from '@motajs/animate';
import type { CustomRenderFunction } from '@motajs/render';
// 一条曲线的名称、颜色与函数
export interface CurveEntry {
label: string;
color: string;
curve: ExcitationCurve;
}
const WIDTH = 408;
const HEIGHT = 190;
const LEFT = 46;
const TOP = 12;
const RIGHT = 12;
const BOTTOM = 36;
// 刻度文字:整数不带小数点,其余最多保留两位
function formatTick(value: number): string {
if (Number.isInteger(value)) return String(value);
return value.toFixed(2).replace(/0+$/, '').replace(/\.$/, '');
}
// 生成绘制坐标轴与多条曲线的 render 函数;纵轴默认 0 到 1,可指定显示范围
export function createCurveRender(
curves: CurveEntry[],
options: { min?: number; max?: number } = {}
): CustomRenderFunction {
const min = options.min ?? 0;
const max = options.max ?? 1;
return canvas => {
const ctx = canvas.ctx;
const plotWidth = WIDTH - LEFT - RIGHT;
const plotHeight = HEIGHT - TOP - BOTTOM;
const bottom = TOP + plotHeight;
const toY = (value: number) =>
TOP + ((max - value) / (max - min)) * plotHeight;
// 背景
ctx.fillStyle = '#101820';
ctx.fillRect(0, 0, WIDTH, HEIGHT);
// 网格
ctx.strokeStyle = '#22304a';
ctx.lineWidth = 1;
for (let i = 0; i <= 4; i++) {
const y = TOP + (plotHeight * i) / 4;
ctx.beginPath();
ctx.moveTo(LEFT, y);
ctx.lineTo(LEFT + plotWidth, y);
ctx.stroke();
const x = LEFT + (plotWidth * i) / 4;
ctx.beginPath();
ctx.moveTo(x, TOP);
ctx.lineTo(x, bottom);
ctx.stroke();
}
// 坐标轴
ctx.strokeStyle = '#7d8ea6';
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(LEFT, TOP);
ctx.lineTo(LEFT, bottom);
ctx.lineTo(LEFT + plotWidth, bottom);
ctx.stroke();
// 刻度
ctx.fillStyle = '#8b98a8';
ctx.font = '11px Verdana';
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
for (let i = 0; i <= 4; i++) {
const value = max - ((max - min) * i) / 4;
const y = TOP + (plotHeight * i) / 4;
ctx.fillText(formatTick(value), LEFT - 8, y);
}
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
ctx.fillText('0', LEFT, bottom + 6);
ctx.fillText('0.5', LEFT + plotWidth / 2, bottom + 6);
ctx.fillText('1', LEFT + plotWidth, bottom + 6);
// 轴名
ctx.fillText('x', LEFT + plotWidth / 2, bottom + 22);
ctx.save();
ctx.translate(12, TOP + plotHeight / 2);
ctx.rotate(-Math.PI / 2);
ctx.textBaseline = 'middle';
ctx.fillText('输出', 0, 0);
ctx.restore();
// 曲线
ctx.lineWidth = 2.5;
for (const entry of curves) {
ctx.beginPath();
ctx.strokeStyle = entry.color;
for (let i = 0; i <= 120; i++) {
const p = i / 120;
const value = entry.curve(p);
const x = LEFT + p * plotWidth;
const y = toY(value);
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.stroke();
}
};
}
@@ -0,0 +1,31 @@
import { pow } from '@motajs/animate';
import { defineComponent, ref } from 'vue';
import { Slider } from '../../../../../packages-user/client-base/src/components/slider';
import CurveLab from './animation-curve-lab';
const EXP_MIN = 0.5;
const EXP_MAX = 4;
// 幂曲线:调整指数,切换四种 CurveMode
export default defineComponent(() => {
const exp = ref(2);
return () => (
<CurveLab
title="pow(exp, mode?)"
subtitle="幂曲线:调整指数与模式"
curve={mode => pow(exp.value, mode)}
bindings={[exp.value]}
supportsMode
>
<text loc={[24, 4]} text="指数 exp" fillStyle="#cfe0ff" />
<Slider
loc={[112, 0, 336, 24]}
v-model:value={exp.value}
min={EXP_MIN}
max={EXP_MAX}
step={0.1}
/>
</CurveLab>
);
});
@@ -0,0 +1,16 @@
import { sec } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveLab from './animation-curve-lab';
// 正割曲线:切换四种 CurveMode,观察快慢分布
export default defineComponent(() => {
return () => (
<CurveLab
title="sec(mode?)"
subtitle="正割曲线:切换模式观察快慢分布"
curve={mode => sec(mode)}
bindings={[]}
supportsMode
/>
);
});
@@ -0,0 +1,31 @@
import { sech } from '@motajs/animate';
import { defineComponent, ref } from 'vue';
import { Slider } from '../../../../../packages-user/client-base/src/components/slider';
import CurveLab from './animation-curve-lab';
const K_MIN = 0.5;
const K_MAX = 4;
// 双曲正割曲线:调整比例参数 k,切换四种 CurveMode
export default defineComponent(() => {
const k = ref(1);
return () => (
<CurveLab
title="sech(k = 1, mode?)"
subtitle="双曲正割曲线:调整 k 与模式"
curve={mode => sech(k.value, mode)}
bindings={[k.value]}
supportsMode
>
<text loc={[24, 4]} text="比例参数 k" fillStyle="#cfe0ff" />
<Slider
loc={[112, 0, 336, 24]}
v-model:value={k.value}
min={K_MIN}
max={K_MAX}
step={0.1}
/>
</CurveLab>
);
});
@@ -0,0 +1,16 @@
import { sin } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveLab from './animation-curve-lab';
// 正弦曲线:切换四种 CurveMode,观察快慢分布
export default defineComponent(() => {
return () => (
<CurveLab
title="sin(mode?)"
subtitle="正弦曲线:切换模式观察快慢分布"
curve={mode => sin(mode)}
bindings={[]}
supportsMode
/>
);
});
@@ -0,0 +1,30 @@
import { step } from '@motajs/animate';
import { defineComponent, ref } from 'vue';
import { Slider } from '../../../../../packages-user/client-base/src/components/slider';
import CurveLab from './animation-curve-lab';
const STEP_MIN = 2;
const STEP_MAX = 12;
// 阶梯曲线:进度每走 1/k,输出跳变一次
export default defineComponent(() => {
const k = ref(5);
return () => (
<CurveLab
title="step(k)"
subtitle="阶梯曲线:每 1/k 段跳变一次"
curve={() => step(k.value)}
bindings={[k.value]}
>
<text loc={[24, 4]} text="阶梯数 k" fillStyle="#cfe0ff" />
<Slider
loc={[112, 0, 336, 24]}
v-model:value={k.value}
min={STEP_MIN}
max={STEP_MAX}
step={1}
/>
</CurveLab>
);
});
@@ -0,0 +1,16 @@
import { tan } from '@motajs/animate';
import { defineComponent } from 'vue';
import CurveLab from './animation-curve-lab';
// 正切曲线:切换四种 CurveMode,观察快慢分布
export default defineComponent(() => {
return () => (
<CurveLab
title="tan(mode?)"
subtitle="正切曲线:切换模式观察快慢分布"
curve={mode => tan(mode)}
bindings={[]}
supportsMode
/>
);
});
@@ -0,0 +1,31 @@
import { tanh } from '@motajs/animate';
import { defineComponent, ref } from 'vue';
import { Slider } from '../../../../../packages-user/client-base/src/components/slider';
import CurveLab from './animation-curve-lab';
const K_MIN = 0.5;
const K_MAX = 4;
// 双曲正切曲线:调整比例参数 k,切换四种 CurveMode
export default defineComponent(() => {
const k = ref(2);
return () => (
<CurveLab
title="tanh(k = 2, mode?)"
subtitle="双曲正切曲线:调整 k 与模式"
curve={mode => tanh(k.value, mode)}
bindings={[k.value]}
supportsMode
>
<text loc={[24, 4]} text="比例参数 k" fillStyle="#cfe0ff" />
<Slider
loc={[112, 0, 336, 24]}
v-model:value={k.value}
min={K_MIN}
max={K_MAX}
step={0.1}
/>
</CurveLab>
);
});
@@ -0,0 +1,51 @@
import { constant, linear, step } from '@motajs/animate';
import { defineComponent } from 'vue';
import { createCurveRender, type CurveEntry } from './animation-curve-plot';
const CURVES: CurveEntry[] = [
{ label: 'linear()', color: '#7ee787', curve: linear() },
{ label: 'step(5)', color: '#f2b84b', curve: step(5) },
{ label: 'constant(0.5)', color: '#c58af9', curve: constant(0.5) }
];
// 基础曲线:线性、阶梯与常数
export default defineComponent(() => {
const render = createCurveRender(CURVES);
return () => (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text loc={[24, 16]} text="基础曲线" fillStyle="#e8f0ff" />
<text
loc={[24, 38]}
text="横轴 progress 0→1;纵轴输出"
fillStyle="#8b98a8"
/>
<custom loc={[36, 64, 408, 190]} render={render} />
{CURVES.map((entry, index) => (
<container
key={entry.label}
loc={[
40 + (index % 2) * 210,
266 + Math.floor(index / 2) * 26,
200,
20
]}
>
<g-line
line={[0, 10, 20, 10]}
strokeStyle={entry.color}
lineWidth={4}
/>
<text
loc={[28, 0]}
text={entry.label}
fillStyle="#cfe0ff"
/>
</container>
))}
</container>
);
});
@@ -0,0 +1,56 @@
import { CurveMode, pow, sec, sin, tan } from '@motajs/animate';
import { defineComponent } from 'vue';
import { createCurveRender, type CurveEntry } from './animation-curve-plot';
const CURVES: CurveEntry[] = [
{ label: 'sin()', color: '#2f6fed', curve: sin(CurveMode.EaseOut) },
{
label: 'pow(2)',
color: '#7ee787',
curve: pow(2, CurveMode.EaseOut)
},
{ label: 'tan()', color: '#f2b84b', curve: tan(CurveMode.EaseOut) },
{ label: 'sec()', color: '#c58af9', curve: sec(CurveMode.EaseOut) }
];
// 缓动曲线:正弦、幂、正切与正割
export default defineComponent(() => {
const render = createCurveRender(CURVES);
return () => (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text loc={[24, 16]} text="缓动曲线" fillStyle="#e8f0ff" />
<text
loc={[24, 38]}
text="横轴 progress 0→1;纵轴输出"
fillStyle="#8b98a8"
/>
<custom loc={[36, 64, 408, 190]} render={render} />
{CURVES.map((entry, index) => (
<container
key={entry.label}
loc={[
40 + (index % 2) * 210,
266 + Math.floor(index / 2) * 26,
200,
20
]}
>
<g-line
line={[0, 10, 20, 10]}
strokeStyle={entry.color}
lineWidth={4}
/>
<text
loc={[28, 0]}
text={entry.label}
fillStyle="#cfe0ff"
/>
</container>
))}
</container>
);
});
@@ -0,0 +1,64 @@
import { CurveMode, cosh, sech, tanh } from '@motajs/animate';
import { defineComponent } from 'vue';
import { createCurveRender, type CurveEntry } from './animation-curve-plot';
const CURVES: CurveEntry[] = [
{
label: 'cosh()',
color: '#2f6fed',
curve: cosh(2, CurveMode.EaseOut)
},
{
label: 'tanh()',
color: '#7ee787',
curve: tanh(2, CurveMode.EaseOut)
},
{
label: 'sech()',
color: '#f2b84b',
curve: sech(1, CurveMode.EaseOut)
}
];
// 双曲曲线:双曲余弦、双曲正切与双曲正割
export default defineComponent(() => {
// 三条曲线都在 0 到 1 之间,纵轴固定为 0 到 1
const render = createCurveRender(CURVES);
return () => (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text loc={[24, 16]} text="双曲曲线" fillStyle="#e8f0ff" />
<text
loc={[24, 38]}
text="横轴 progress 0→1;纵轴输出"
fillStyle="#8b98a8"
/>
<custom loc={[36, 64, 408, 190]} render={render} />
{CURVES.map((entry, index) => (
<container
key={entry.label}
loc={[
40 + (index % 2) * 210,
266 + Math.floor(index / 2) * 26,
200,
20
]}
>
<g-line
line={[0, 10, 20, 10]}
strokeStyle={entry.color}
lineWidth={4}
/>
<text
loc={[28, 0]}
text={entry.label}
fillStyle="#cfe0ff"
/>
</container>
))}
</container>
);
});
@@ -0,0 +1,123 @@
import { CurveMode, sin } from '@motajs/animate';
import { cycledTransition } from '@motajs/render-vue';
import { defineComponent, ref, watch } from 'vue';
import { Slider } from '../../../../../packages-user/client-base/src/components/slider';
// 循环渐变:两个滑动条调整循环的起点与终点
export default defineComponent(() => {
const minValue = ref(0.25);
const maxValue = ref(0.9);
const glow = cycledTransition(
minValue.value,
maxValue.value,
900,
sin(CurveMode.EaseOut)
)!;
const applyRange = () => {
// 两个端点保持一前一后,避免区间塌成一个点
if (maxValue.value - minValue.value < 0.05) {
if (minValue.value <= 0.95) {
maxValue.value = minValue.value + 0.05;
} else {
minValue.value = maxValue.value - 0.05;
}
}
glow.setRange(minValue.value, maxValue.value);
};
watch([minValue, maxValue], applyRange);
return () => {
const trackLeft = 64;
const trackWidth = 352;
const trackY = 130;
const minX = trackLeft + minValue.value * trackWidth;
const maxX = trackLeft + maxValue.value * trackWidth;
const currentX = trackLeft + glow.ref.value * trackWidth;
return (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text
loc={[24, 16]}
text="cycledTransition:循环渐变"
fillStyle="#e8f0ff"
/>
<text
loc={[24, 40]}
text="拖动两个滑动条调整循环的起点与终点"
fillStyle="#8b98a8"
/>
<text loc={[24, 76]} text="当前值" fillStyle="#cfe0ff" />
<text
loc={[24, 98]}
text={glow.ref.value.toFixed(2)}
fillStyle="#7ee787"
/>
<g-line
line={[trackLeft, trackY, trackLeft + trackWidth, trackY]}
strokeStyle="#26364d"
lineWidth={8}
lineCap="round"
/>
<g-line
line={[minX, trackY, maxX, trackY]}
strokeStyle="#2f6fed"
lineWidth={8}
lineCap="round"
/>
<g-line
line={[minX, trackY - 12, minX, trackY + 12]}
strokeStyle="#8fb6ff"
lineWidth={2}
/>
<g-line
line={[maxX, trackY - 12, maxX, trackY + 12]}
strokeStyle="#8fb6ff"
lineWidth={2}
/>
<g-circle circle={[currentX, trackY, 9]} fillStyle="#f2b84b" />
<text
loc={[minX, trackY + 22]}
anc={[0.5, 0]}
text={`min ${minValue.value.toFixed(2)}`}
fillStyle="#8fb6ff"
/>
<text
loc={[maxX, trackY + 22]}
anc={[0.5, 0]}
text={`max ${maxValue.value.toFixed(2)}`}
fillStyle="#8fb6ff"
/>
<text loc={[64, 196]} text="起点" fillStyle="#cfe0ff" />
<Slider
loc={[108, 192, 300, 24]}
v-model:value={minValue.value}
min={0}
max={1}
step={0.05}
valueWidth={44}
filledStyle="#2f6fed"
emptyStyle="#26364d"
/>
<text loc={[64, 244]} text="终点" fillStyle="#cfe0ff" />
<Slider
loc={[108, 240, 300, 24]}
v-model:value={maxValue.value}
min={0}
max={1}
step={0.05}
valueWidth={44}
filledStyle="#2f6fed"
emptyStyle="#26364d"
/>
</container>
);
};
});
@@ -0,0 +1,137 @@
import { EndRelation } from '@motajs/animate';
import { useTransition } from '@motajs/render-vue';
import { defineComponent, onMounted, ref } from 'vue';
// 半程曲线在 1 处输出 0.5,回程曲线在 1 处回到 0
const HALF = (p: number) => p * 0.5;
const RETURN = (p: number) => Math.sin(p * Math.PI) * 0.5;
const curves = [
{ label: '半程曲线', curve: HALF, time: 600 },
{ label: '回程曲线', curve: RETURN, time: 900 }
];
// 同一目标配同一条曲线,比较 Target 与 Curve 两种结尾参考
export default defineComponent(() => {
const targetValue = ref(0);
const curveValue = ref(0);
const index = ref(0);
const transition = useTransition()!;
const play = () => {
const item = curves[index.value];
targetValue.value = 0;
curveValue.value = 0;
transition
.transition(targetValue)
.curve(item.curve)
.to(1, item.time, EndRelation.Target);
transition
.transition(curveValue)
.curve(item.curve)
.to(1, item.time, EndRelation.Curve);
};
const next = () => {
index.value = (index.value + 1) % curves.length;
play();
};
onMounted(() => {
requestAnimationFrame(play);
});
return () => {
const item = curves[index.value];
const endpoint = item.curve(1);
const targetX = 24 + targetValue.value * 400;
const curveX = 24 + curveValue.value * 400;
const endX = 24 + endpoint * 400;
return (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text
loc={[24, 16]}
text="Transition:EndRelation"
fillStyle="#e8f0ff"
/>
<text
loc={[24, 40]}
text="同一条曲线:Target 结束于目标值,Curve 停在曲线终点"
fillStyle="#8b98a8"
/>
<text
loc={[24, 72]}
text="Target:结束写目标值"
fillStyle="#cfe0ff"
/>
<g-rect loc={[24, 96, 400, 14]} fillStyle="#26364d" />
<g-rect
loc={[24, 96, 400 * targetValue.value, 14]}
fillStyle="#2f6fed"
/>
<g-rect loc={[targetX - 1, 86, 2, 34]} fillStyle="#f2b84b" />
<text
loc={[24, 120]}
text={`当前 ${targetValue.value.toFixed(2)} · 终点 1.00`}
fillStyle="#8fb6ff"
/>
<text
loc={[24, 150]}
text="Curve:结束写曲线终点"
fillStyle="#cfe0ff"
/>
<g-rect loc={[24, 174, 400, 14]} fillStyle="#26364d" />
<g-rect
loc={[24, 174, 400 * curveValue.value, 14]}
fillStyle="#7ee787"
/>
<g-rect loc={[curveX - 1, 164, 2, 34]} fillStyle="#58c4dd" />
<g-rect loc={[endX - 1, 164, 2, 34]} fillStyle="#f2b84b" />
<text
loc={[24, 198]}
text={`当前 ${curveValue.value.toFixed(2)} · 终点 ${endpoint.toFixed(2)}`}
fillStyle="#8fb6ff"
/>
<text
loc={[24, 226]}
text={`曲线:${item.label} · ${item.time}ms · 终点 ${endpoint.toFixed(2)}`}
fillStyle="#8b98a8"
/>
<container
loc={[24, 254, 100, 30]}
cursor="pointer"
onClick={play}
>
<g-rectr
loc={[0, 0, 100, 30]}
circle={[8]}
fillStyle="#2f6fed"
/>
<text loc={[14, 7]} text="重播" fillStyle="#ffffff" />
</container>
<container
loc={[140, 254, 160, 30]}
cursor="pointer"
onClick={next}
>
<g-rectr
loc={[0, 0, 160, 30]}
circle={[8]}
fillStyle="#33465f"
/>
<text
loc={[14, 7]}
text="换曲线与时长"
fillStyle="#e8f0ff"
/>
</container>
</container>
);
};
});
@@ -0,0 +1,93 @@
import { linear, sin } from '@motajs/animate';
import { useTransition } from '@motajs/render-vue';
import { defineComponent, onMounted, ref } from 'vue';
// 单值渐变:Transition 让当前值走向目标值
export default defineComponent(() => {
const value = ref(0.18);
const target = ref(0.82);
const transition = useTransition()!;
// 设定新的目标值,执行器从当前值继续渐变
const moveTo = (next: number, curve = sin()) => {
target.value = next;
transition.transition(value).curve(curve).to(next, 900);
};
onMounted(() => {
// 等执行器绑定到根激励源后再启动首段渐变
requestAnimationFrame(() => moveTo(0.82));
});
return () => {
const current = value.value;
const goal = target.value;
const targetX = 40 + goal * 400;
return (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text
loc={[24, 16]}
text="Transition:单值渐变"
fillStyle="#e8f0ff"
/>
<text
loc={[24, 40]}
text="当前值由执行器逐帧写入,目标值由 to 设定"
fillStyle="#8b98a8"
/>
<text loc={[40, 80]} text="当前值" fillStyle="#cfe0ff" />
<text
loc={[40, 100]}
text={current.toFixed(2)}
fillStyle="#8fb6ff"
/>
<text loc={[160, 80]} text="目标值" fillStyle="#cfe0ff" />
<text
loc={[160, 100]}
text={goal.toFixed(2)}
fillStyle="#f2b84b"
/>
<g-rect loc={[40, 140, 400, 16]} fillStyle="#26364d" />
<g-rect
loc={[40, 140, 400 * current, 16]}
fillStyle="#2f6fed"
/>
<g-rect loc={[targetX - 1, 128, 2, 40]} fillStyle="#f2b84b" />
<g-circle circle={[targetX, 148, 6]} fillStyle="#f2b84b" />
<container
loc={[40, 208, 120, 32]}
onClick={() => moveTo(0.82)}
>
<g-rectr
loc={[0, 0, 120, 32]}
circle={[8]}
fillStyle="#2f6fed"
/>
<text loc={[12, 8]} text="去 0.82" fillStyle="#ffffff" />
</container>
<container
loc={[176, 208, 120, 32]}
onClick={() => moveTo(0.18, linear())}
>
<g-rectr
loc={[0, 0, 120, 32]}
circle={[8]}
fillStyle="#33465f"
/>
<text loc={[12, 8]} text="回 0.18" fillStyle="#e8f0ff" />
</container>
<text
loc={[40, 264]}
text={`当前值 ${current.toFixed(2)} → 目标值 ${goal.toFixed(2)}`}
fillStyle="#8b98a8"
/>
</container>
);
};
});
@@ -0,0 +1,155 @@
import { ExcitationVariator, RafExcitation } from '@motajs/animate';
import { defineComponent, onUnmounted, ref } from 'vue';
// 变速曲线:最后两次激励时间戳与时间差
export default defineComponent(() => {
const speed = ref(1);
const progress = ref(0);
const prevTs = ref(0);
const lastTs = ref(0);
const gap = ref(0);
const running = ref(false);
let base = 0;
let hasBase = false;
let hasPrev = false;
let curveStart = 0;
const curveTime = 3000;
const source = new RafExcitation();
const variator = new ExcitationVariator();
variator.bindExcitation(source);
variator.add({
excited(payload: number) {
if (!hasBase) {
base = payload;
hasBase = true;
}
if (hasPrev) prevTs.value = lastTs.value;
lastTs.value = payload - base;
if (hasPrev) gap.value = lastTs.value - prevTs.value;
hasPrev = true;
speed.value = variator.speed;
if (running.value) {
const elapsed = source.payload() - curveStart;
progress.value = Math.min(elapsed / curveTime, 1);
if (progress.value >= 1) running.value = false;
}
}
});
const runCurve = () => {
if (running.value) return;
curveStart = source.payload();
running.value = true;
progress.value = 0;
void variator.curveSpeed(p => 1.5 - 1.25 * p, curveTime);
};
const resetSpeed = () => {
variator.endAllCurves();
variator.setSpeed(1);
speed.value = 1;
running.value = false;
progress.value = 0;
};
onUnmounted(() => {
variator.destroy();
source.destroy();
});
return () => (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text
loc={[24, 16]}
text="curveSpeed:时间流速随时间变化"
fillStyle="#e8f0ff"
/>
<text
loc={[24, 40]}
text="曲线速度从 1.5× 降到 0.25×,持续 3 秒"
fillStyle="#8b98a8"
/>
<text
loc={[40, 72]}
text="输出端时间(相对开始)"
fillStyle="#cfe0ff"
/>
<text
loc={[40, 98]}
text={`${lastTs.value.toFixed(1)} ms`}
fillStyle="#8fb6ff"
/>
<text loc={[260, 72]} text="当前速度" fillStyle="#cfe0ff" />
<text
loc={[260, 98]}
text={`${speed.value.toFixed(2)}×`}
fillStyle="#7ee787"
/>
<g-rect loc={[40, 122, 400, 92]} fillStyle="#1b2433" />
<text loc={[52, 134]} text="最后两次激励" fillStyle="#cfe0ff" />
<text
loc={[52, 158]}
text={`上次 = ${prevTs.value.toFixed(1)} ms`}
fillStyle="#8fb6ff"
/>
<text
loc={[52, 180]}
text={`本次 = ${lastTs.value.toFixed(1)} ms`}
fillStyle="#8fb6ff"
/>
<text loc={[252, 158]} text="时间差" fillStyle="#cfe0ff" />
<text
loc={[252, 180]}
text={`${gap.value.toFixed(2)} ms`}
fillStyle="#f2b84b"
/>
<text
loc={[40, 220]}
text="速度越高,输出端时间推进越快,时间差越大"
fillStyle="#8b98a8"
/>
<text loc={[40, 248]} text="曲线进度" fillStyle="#cfe0ff" />
<g-rect loc={[40, 266, 300, 10]} fillStyle="#26364d" />
<g-rect
loc={[40, 266, 300 * progress.value, 10]}
fillStyle="#7ee787"
/>
<text
loc={[352, 262]}
text={`${Math.round(progress.value * 100)}%`}
fillStyle="#8fb6ff"
/>
<container loc={[40, 286, 140, 32]} onClick={runCurve}>
<g-rectr
loc={[0, 0, 140, 32]}
circle={[8]}
fillStyle={running.value ? '#26364d' : '#2f6fed'}
/>
<text
loc={[26, 8]}
text={running.value ? '曲线运行中' : '运行曲线'}
fillStyle="#ffffff"
/>
</container>
<container loc={[196, 286, 140, 32]} onClick={resetSpeed}>
<g-rectr
loc={[0, 0, 140, 32]}
circle={[8]}
fillStyle="#33465f"
/>
<text loc={[26, 8]} text="重置为 1×" fillStyle="#e8f0ff" />
</container>
</container>
);
});
@@ -0,0 +1,114 @@
import { ExcitationDivider, IntervalExcitation } from '@motajs/animate';
import { defineComponent, onUnmounted, ref } from 'vue';
// 分频器:统计输入源激励次数与输出端转发次数
export default defineComponent(() => {
const divider = ref(1);
const upCount = ref(0);
const downCount = ref(0);
const upPayload = ref(0);
const downPayload = ref(0);
const source = new IntervalExcitation(200);
const splitter = new ExcitationDivider<number>();
splitter.bindExcitation(source);
source.add({
excited(payload: number) {
upCount.value += 1;
upPayload.value = payload;
}
});
splitter.add({
excited(payload: number) {
downCount.value += 1;
downPayload.value = payload;
}
});
const changeDivider = (value: number) => {
splitter.setDivider(value);
divider.value = value;
};
onUnmounted(() => {
splitter.unbindExcitation();
splitter.destroy();
source.destroy();
});
const options = [1, 2, 3, 5];
return () => (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text
loc={[24, 16]}
text="ExcitationDivider:输入与转发次数"
fillStyle="#e8f0ff"
/>
<text
loc={[24, 40]}
text="分频器只转发部分激励,负载本身不变"
fillStyle="#8b98a8"
/>
<text loc={[40, 76]} text="输入源原始载荷" fillStyle="#cfe0ff" />
<text
loc={[40, 102]}
text={`${Math.round(upPayload.value)} ms`}
fillStyle="#8fb6ff"
/>
<text loc={[40, 146]} text="输入源次数" fillStyle="#cfe0ff" />
<text
loc={[40, 172]}
text={String(upCount.value)}
fillStyle="#8fb6ff"
/>
<text loc={[260, 76]} text="输出端收到的载荷" fillStyle="#f2b84b" />
<text
loc={[260, 102]}
text={`${Math.round(downPayload.value)} ms`}
fillStyle="#f2b84b"
/>
<text loc={[260, 146]} text="输出端次数" fillStyle="#f2b84b" />
<text
loc={[260, 172]}
text={String(downCount.value)}
fillStyle="#f2b84b"
/>
<text loc={[40, 210]} text="当前分频比" fillStyle="#cfe0ff" />
<text
loc={[40, 236]}
text={`每 ${divider.value} 次输入 → 1 次输出`}
fillStyle="#7ee787"
/>
{options.map((value, index) => {
const active = divider.value === value;
return (
<container
key={value}
loc={[40 + index * 72, 270, 64, 32]}
onClick={() => changeDivider(value)}
>
<g-rectr
loc={[0, 0, 64, 32]}
circle={[8]}
fillStyle={active ? '#2f6fed' : '#33465f'}
/>
<text
loc={[20, 8]}
text={`÷${value}`}
fillStyle="#ffffff"
/>
</container>
);
})}
</container>
);
});
@@ -0,0 +1,84 @@
import { RafExcitation } from '@motajs/animate';
import { defineComponent, onUnmounted, ref } from 'vue';
// 载荷演示:RafExcitation 每帧广播当前时间戳
export default defineComponent(() => {
const now = ref(0);
const start = ref(0);
const frames = ref(0);
const frameGap = ref(0);
let last = 0;
let hasLast = false;
const source = new RafExcitation();
source.add({
excited(payload: number) {
if (frames.value === 0) start.value = payload;
if (hasLast) frameGap.value = payload - last;
last = payload;
hasLast = true;
now.value = payload;
frames.value += 1;
}
});
onUnmounted(() => {
source.destroy();
});
return () => (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text
loc={[24, 16]}
text="RafExcitation:当前载荷"
fillStyle="#e8f0ff"
/>
<text
loc={[24, 40]}
text="每帧广播 requestAnimationFrame 的时间戳"
fillStyle="#8b98a8"
/>
<text loc={[40, 84]} text="当前载荷" fillStyle="#cfe0ff" />
<text
loc={[40, 112]}
text={`${Math.round(now.value)} ms`}
fillStyle="#8fb6ff"
/>
<text loc={[260, 84]} text="帧间隔" fillStyle="#f2b84b" />
<text
loc={[260, 112]}
text={`${frameGap.value.toFixed(1)} ms`}
fillStyle="#f2b84b"
/>
<text loc={[40, 164]} text="距开始" fillStyle="#cfe0ff" />
<text
loc={[40, 192]}
text={`${Math.round(now.value - start.value)} ms`}
fillStyle="#8fb6ff"
/>
<text loc={[260, 164]} text="帧数" fillStyle="#cfe0ff" />
<text
loc={[260, 192]}
text={String(frames.value)}
fillStyle="#8fb6ff"
/>
<text
loc={[40, 248]}
text="帧间隔 = 本次时间戳 − 上一次时间戳"
fillStyle="#8b98a8"
/>
<text
loc={[40, 278]}
text="它反映相邻两帧之间过了多久"
fillStyle="#8b98a8"
/>
</container>
);
});
@@ -0,0 +1,131 @@
import { ExcitationVariator, RafExcitation } from '@motajs/animate';
import { defineComponent, onUnmounted, ref } from 'vue';
// 变速器:输出端连续两次时间的差值
export default defineComponent(() => {
const speed = ref(1);
const inputNow = ref(0);
const prevOut = ref(0);
const currOut = ref(0);
const gap = ref(0);
const hasPrev = ref(false);
const source = new RafExcitation();
const variator = new ExcitationVariator();
variator.bindExcitation(source);
let lastOut = 0;
source.add({
excited(payload: number) {
inputNow.value = payload;
}
});
variator.add({
excited(payload: number) {
if (hasPrev.value) {
prevOut.value = lastOut;
gap.value = payload - lastOut;
}
currOut.value = payload;
lastOut = payload;
hasPrev.value = true;
speed.value = variator.speed;
}
});
const changeSpeed = (value: number) => {
variator.setSpeed(value);
speed.value = value;
};
onUnmounted(() => {
variator.destroy();
source.destroy();
});
return () => (
<container loc={[0, 0, 480, 320]}>
<g-rect loc={[0, 0, 480, 320]} fillStyle="#141a22" />
<text
loc={[24, 16]}
text="ExcitationVariator:输出端连续两次时间"
fillStyle="#e8f0ff"
/>
<text
loc={[24, 40]}
text="变速器按速度换算输入源时间,再推进接收方"
fillStyle="#8b98a8"
/>
<text loc={[40, 78]} text="输入源当前时间" fillStyle="#cfe0ff" />
<text
loc={[40, 102]}
text={`${Math.round(inputNow.value)} ms`}
fillStyle="#8fb6ff"
/>
<g-rect loc={[40, 130, 400, 104]} fillStyle="#1b2433" />
<text loc={[52, 140]} text="上次时间" fillStyle="#cfe0ff" />
<text
loc={[52, 164]}
text={hasPrev.value ? `${prevOut.value.toFixed(1)} ms` : '—'}
fillStyle="#8fb6ff"
/>
<text loc={[180, 140]} text="本次时间" fillStyle="#cfe0ff" />
<text
loc={[180, 164]}
text={`${currOut.value.toFixed(1)} ms`}
fillStyle="#8fb6ff"
/>
<text loc={[300, 140]} text="时间差" fillStyle="#f2b84b" />
<text
loc={[300, 164]}
text={hasPrev.value ? `${gap.value.toFixed(2)} ms` : '—'}
fillStyle="#f2b84b"
/>
<text
loc={[52, 198]}
text="速度越高,输出端相邻两次的时间差越大"
fillStyle="#8b98a8"
/>
<text loc={[40, 240]} text="当前速度" fillStyle="#cfe0ff" />
<text
loc={[128, 240]}
text={`${speed.value.toFixed(2)}×`}
fillStyle="#7ee787"
/>
<container loc={[40, 274, 88, 32]} onClick={() => changeSpeed(0.5)}>
<g-rectr
loc={[0, 0, 88, 32]}
circle={[8]}
fillStyle={speed.value === 0.5 ? '#2f6fed' : '#33465f'}
/>
<text loc={[18, 8]} text="0.5×" fillStyle="#ffffff" />
</container>
<container loc={[144, 274, 88, 32]} onClick={() => changeSpeed(1)}>
<g-rectr
loc={[0, 0, 88, 32]}
circle={[8]}
fillStyle={speed.value === 1 ? '#2f6fed' : '#33465f'}
/>
<text loc={[24, 8]} text="1×" fillStyle="#ffffff" />
</container>
<container loc={[248, 274, 88, 32]} onClick={() => changeSpeed(2)}>
<g-rectr
loc={[0, 0, 88, 32]}
circle={[8]}
fillStyle={speed.value === 2 ? '#2f6fed' : '#33465f'}
/>
<text loc={[18, 8]} text="2×" fillStyle="#ffffff" />
</container>
</container>
);
});
+26
View File
@@ -376,6 +376,10 @@ export default defineConfig({
text: '自定义组件',
link: '/render-guide/advanced/custom-components'
},
{
text: '动画',
link: '/render-guide/advanced/animation'
},
{
text: 'UI 系统',
link: '/render-guide/advanced/ui-system'
@@ -409,6 +413,28 @@ export default defineConfig({
link: '/render-guide/advanced/inventory-example-6-animation-and-register'
}
]
},
{
text: '渲染底层',
collapsed: false,
items: [
{
text: '动画曲线',
link: '/render-guide/internals/animation-curves'
},
{
text: '动画激励',
link: '/render-guide/internals/animation-excitation'
},
{
text: '动画执行器',
link: '/render-guide/internals/animation-runner'
},
{
text: '渐变执行器',
link: '/render-guide/internals/animation-transition'
}
]
}
]
},
+389
View File
@@ -0,0 +1,389 @@
# 动画
动画就是一系列数据按照指定方式变化:位置、透明度、颜色与进度条长度,都可以随时间连续改变。曲线决定「时间从起点走到终点时,数据按什么方式变化」;把数据与曲线交给动画系统,值就会平滑过渡,而不是瞬间跳过去。
本篇先讲曲线如何把时间映射成数据,再按基础、缓动与双曲三组介绍内置曲线的参数与形状,最后讲三个高层接口 `transitioned`、`transitionedColor` 与 `cycledTransition`。更底层的执行器与激励源见渲染底层。
## 前置知识
阅读本篇前,建议先读完:
- [响应式](./reactivity.md)
- [UI 入门](../basics/ui-basics.md)
## 动画的本质与曲线
一个动画由两部分组成:一份要变化的数据,和一条把时间进度映射成数据取值的曲线。时间进度通常叫 `progress`,从 `0`(开始)走到 `1`(结束)。曲线接收 `progress`,返回一个数;动画系统按这个返回值,在起始值与目标值之间取出当前值。
```ts
type ExcitationCurve = (progress: number) => number;
```
`progress` 在 `0` 到 `1` 之间,曲线的输出不要求也落在 `0` 到 `1`:输出可以超出这个范围,所以过程中可以低于起始值或高于目标值,也可以多次起伏。曲线只决定过渡过程,不决定动画最终落在哪个值;最终落点由使用曲线的动画接口给出。
内置曲线都从 `@motajs/animate` 导入。不带 `mode` 参数的曲线直接返回一条固定形状的曲线;带 `mode` 参数的曲线会在内部套用下面的曲线模式。
## 曲线模式
曲线本身只保证「缓进快出」这一种基本形状。给它套一个 `CurveMode`,就能改变快慢分布。`CurveMode` 是曲线的模式枚举,默认 `CurveMode.EaseIn`。
| 模式 | 含义 | 形状 |
| ---------------------- | ---------------- | ------------------------------ |
| `CurveMode.EaseIn` | 缓进快出 | 从起点慢慢加速,越接近终点越快 |
| `CurveMode.EaseOut` | 快进缓出 | 起步快,接近终点逐渐减速 |
| `CurveMode.EaseInOut` | 缓进缓出,中间快 | 两端慢、中段最快 |
| `CurveMode.EaseCenter` | 快进快出,中间缓 | 两端快、中段最慢 |
这四种模式都从 `0` 开始、到 `1` 结束,区别只在过程中的快慢分布:`EaseIn` 越走越快,`EaseOut` 越走越慢,`EaseInOut` 两端慢、中段快,`EaseCenter` 两端快、中段慢。`CurveMode` 只改变形状,不改变时长与起止值;同一个曲线换模式只是让过程中快慢不同。各模式如何由一条缓进快出曲线换算得到,见[动画曲线](../internals/animation-curves.md#曲线模式)。
下面的演示用同一条正弦曲线,点四个按钮在四种模式之间切换。曲线连续变化,可以直观看出快慢分布。
<ClientOnly>
<RenderDemo :loader="curveModesLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
## 内置曲线
下面按基础、缓动与双曲三组列出参数与形状;同一组的多条曲线画在一张图里,便于对照。
### 基础曲线
三条基础曲线不接收 `mode` 参数,形状直接由参数决定。
| 曲线 | 参数 |
| ------------- | --------------------- |
| `linear()` | 无 |
| `step(k)` | `k`:阶梯数,取正整数 |
| `constant(k)` | `k`:常数输出值 |
<ClientOnly>
<RenderDemo :loader="basicCurvesLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 缓动曲线
四条曲线都以「缓进快出」为基准,并接收可选的 `mode`;不传时默认 `CurveMode.EaseIn`。它们从 `0` 上升到 `1`,上升速度不同。
| 曲线 | 参数 |
| ----------------- | ------------------------------------ |
| `sin(mode?)` | `mode` 可选,默认 `CurveMode.EaseIn` |
| `tan(mode?)` | `mode` 可选,默认 `CurveMode.EaseIn` |
| `sec(mode?)` | `mode` 可选,默认 `CurveMode.EaseIn` |
| `pow(exp, mode?)` | `exp` 必需,指数;`mode` 可选 |
<ClientOnly>
<RenderDemo :loader="easingCurvesLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 双曲曲线
三条双曲曲线同样接收可选的 `mode`,默认 `CurveMode.EaseIn`。`k` 是比例参数。
| 曲线 | 参数 |
| -------------------- | -------------------------------------------- |
| `cosh(k = 2, mode?)` | `k` 默认 `2`;`mode` 默认 `CurveMode.EaseIn` |
| `tanh(k = 2, mode?)` | `k` 默认 `2`;`mode` 默认 `CurveMode.EaseIn` |
| `sech(k = 1, mode?)` | `k` 默认 `1`;`mode` 默认 `CurveMode.EaseIn` |
<ClientOnly>
<RenderDemo :loader="specialCurvesLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
曲线公式、模式换算与单条曲线的行为见[动画曲线](../internals/animation-curves.md)。
## 数值渐变
界面里经常需要让一个数值在两次状态之间平滑变化,例如透明度从 `0.25` 到 `1`、圆点从左边移到右边。自己管理执行器、选择对象、绑定激励源会很啰嗦;`transitioned` 把这些收进一个控制器:你只需要告诉它「现在去哪个值」,它负责在当前值与目标值之间平滑推进。
### 获取控制器
先创建控制器,并给它一个初始值、一次变化默认用多久,以及过程中用哪条曲线:
```tsx
// setup
import { transitioned } from '@motajs/render-vue';
import { CurveMode, sin } from '@motajs/animate';
// 初始值 0.25,默认 600ms,曲线用 sin()
const alpha = transitioned(0.25, 600, sin(CurveMode.EaseOut))!;
```
`transitioned(value, time, curve)` 返回一个数值渐变控制器,类型是 `ITransitionedController<number> | null`:`value` 是初始值,`time` 是默认时长(毫秒),`curve` 是速率曲线。它只在组件 `setup` 中调用;在 `setup` 中返回值一定非空,所以这里用 `!` 收窄类型。返回的控制器带一个响应式引用 `ref`(类型 `Ref<number>`),渲染时读 `alpha.ref.value` 就能拿到当前值。
### 执行渐变动画
控制器拿到后,当前值就是初始值。要让数值走向新目标,调用 `set(value, time?)`;省略 `time` 时使用控制器的默认时长:
```tsx
// setup
const expand = () => {
// 从当前值走向 1,使用创建时的 600ms
alpha.set(1);
};
// 组件内容
<g-rect
loc={[40, 92, 120, 88]}
fillStyle="#2f6fed"
alpha={alpha.ref.value}
onClick={expand}
/>;
```
调用 `set(1)` 后,控制器从调用时的当前值出发,在 600ms 内走向 1;渲染函数读 `alpha.ref.value`,所以矩形的透明度会跟着变化。动画进行中再次 `set`,会从当时的当前值转向新目标;`time` 为 `0` 时直接落到目标值。
### 设置渐变参数
如果某一次变化想用不同节奏,或者之后都换一条曲线、一个时长,可以在下一次 `set` 前调用 `mode(curve)` 或 `setTime(time)`:
```tsx
// setup
import { linear } from '@motajs/animate';
// 这一次改用 300ms
alpha.set(0.4, 300);
// 之后的 set 都改用线性曲线与 1200ms
alpha.mode(linear());
alpha.setTime(1200);
```
`mode(curve)` 替换后续 `set` 使用的速率曲线;`setTime(time)` 替换后续 `set` 的默认时长。两者只影响之后的调用,不会重设当前正在进行的渐变。
把三步连起来,就是一次完整的数值渐变。下面的示例同时驱动透明度、位置与进度条:
```tsx
// setup
import { transitioned } from '@motajs/render-vue';
import { CurveMode, linear, sin } from '@motajs/animate';
const alpha = transitioned(0.25, 600, sin(CurveMode.EaseOut))!;
const slide = transitioned(0, 600, sin(CurveMode.EaseOut))!;
const bar = transitioned(0.3, 600, sin(CurveMode.EaseOut))!;
const expand = () => {
alpha.set(1);
slide.set(1, 300);
bar.set(1);
};
bar.mode(linear());
bar.setTime(1200);
// 组件内容
<g-rect loc={[40, 92, 120, 88]} fillStyle="#2f6fed" alpha={alpha.ref.value} />
<g-circle
circle={[204 + slide.ref.value * 192, 140, 12]}
fillStyle="#f2b84b"
/>
<g-rect
loc={[40, 234, 280 * bar.ref.value, 12]}
fillStyle="#7ee787"
/>
```
下面的 live 用三组元素展示 `alpha`、位置与进度条的渐变。
<ClientOnly>
<RenderDemo :loader="alphaLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
## 颜色渐变
颜色字符串不能直接做数值加减;自己拆成红、绿、蓝、透明四个通道再分别推进,也很麻烦。`transitionedColor` 把颜色当作一个整体:它内部拆通道、同步推进,最后再拼回颜色字符串。
### 获取颜色控制器
```tsx
// setup
import { transitionedColor } from '@motajs/render-vue';
import { CurveMode, sin } from '@motajs/animate';
const fill = transitionedColor('#2f6fed', 600, sin(CurveMode.EaseOut))!;
```
`transitionedColor(color, time, curve)` 返回一个颜色渐变控制器,类型是 `ITransitionedController<string> | null`。`color` 是初始颜色,`time` 是默认时长,`curve` 是速率曲线。它返回的控制器与数值渐变同形,但 `ref.value` 是当前颜色字符串,可以直接交给 `fillStyle`、`strokeStyle`。
支持的颜色写法有十六进制 `#rgb`、`#rgba`、`#rrggbb`、`#rrggbbaa`,以及 `rgb(r, g, b)` 与 `rgba(r, g, b, a)`。只支持这些写法;其他格式不会按预期渐变。
### 执行颜色渐变
```tsx
// setup
const warm = () => {
fill.set('#f2b84b');
};
// 组件内容
<g-rect loc={[40, 80, 180, 140]} fillStyle={fill.ref.value} onClick={warm} />;
```
调用 `set` 后,控制器从当前颜色走向目标颜色;渲染函数读 `fill.ref.value` 得到中间颜色。`set`、`mode`、`setTime` 的用法与数值渐变一致。
### 设置颜色渐变参数
```tsx
// setup
import { linear } from '@motajs/animate';
// 这一次改用 300ms
fill.set('#7ee787', 300);
// 之后的 set 都改用线性曲线与 1200ms
fill.mode(linear());
fill.setTime(1200);
```
`set` 的第二个参数只覆盖这一次的时长;`mode` 与 `setTime` 改的是之后的调用。
把填充色与描边色放进同一个示例:
```tsx
// setup
import { transitionedColor } from '@motajs/render-vue';
import { CurveMode, sin } from '@motajs/animate';
const fill = transitionedColor('#2f6fed', 600, sin(CurveMode.EaseOut))!;
const stroke = transitionedColor(
'rgba(242, 184, 75, 0.9)',
600,
sin(CurveMode.EaseOut)
)!;
fill.set('#f2b84b');
stroke.set('#7ee787');
// 组件内容
<g-rect loc={[40, 80, 180, 140]} fillStyle={fill.ref.value} />
<g-circle
circle={[320, 150, 56]}
stroke
strokeStyle={stroke.ref.value}
lineWidth={10}
/>
```
下面的 live 同时渐变填充色与描边色。
<ClientOnly>
<RenderDemo :loader="colorLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
## 循环渐变
呼吸灯、闪烁这类效果需要数值在两个端点之间反复往返。每次到端点都手动重设目标,很容易接不上;`cycledTransition` 把往返过程包成一个自动循环的控制器。
### 获取循环控制器
```tsx
// setup
import { cycledTransition } from '@motajs/render-vue';
import { CurveMode, sin } from '@motajs/animate';
// 在 0.25 与 1 之间往返,单程 900ms
const glow = cycledTransition(0.25, 1, 900, sin(CurveMode.EaseOut))!;
```
`cycledTransition(min, max, time, curve, maxStart = false)` 返回一个循环渐变控制器,类型是 `ICycledTransitionController | null`。`min` 与 `max` 是循环的两个端点,`time` 是单程耗时(毫秒),`curve` 是单程使用的速率曲线;`maxStart` 为 `true` 时从 `max` 开始,否则从 `min` 开始。控制器返回后会自动开始循环,组件卸载时停止,不需要手动清理。
### 读取循环值
循环已经自动开始,渲染时读 `glow.ref.value` 就能拿到当前值:
```tsx
// 组件内容
<g-circle circle={[180, 150, 80]} fillStyle="#2f6fed" alpha={glow.ref.value} />
```
这个圆形的透明度会在 0.25 与 1 之间反复变化。到端点后控制器会自动把目标切到另一端,不需要再调用 `set`。
### 设置循环参数
```tsx
// setup
import { linear } from '@motajs/animate';
const narrow = () => {
glow.setRange(0.5, 1);
};
glow.mode(linear());
glow.setTime(1200);
// 组件内容
<g-circle
circle={[180, 150, 80]}
fillStyle="#2f6fed"
alpha={glow.ref.value}
onClick={narrow}
/>;
```
`setRange(min, max)` 修改循环的两个端点,并立即按新区间重新确定这一次的目标;`mode(curve)` 与 `setTime(time)` 修改后续单程使用的曲线与时长。
把两个循环放进同一个示例:
```tsx
// setup
import { cycledTransition } from '@motajs/render-vue';
import { CurveMode, linear, sin } from '@motajs/animate';
const glow = cycledTransition(0.25, 1, 900, sin(CurveMode.EaseOut))!;
const core = cycledTransition(0.5, 1, 900, linear(), true)!;
const widen = () => {
glow.setRange(0.5, 1);
};
// 组件内容
<g-circle circle={[180, 150, 80]} fillStyle="#2f6fed" alpha={glow.ref.value} />
<g-circle circle={[180, 150, 38]} fillStyle="#f2b84b" alpha={core.ref.value} />
```
下面的 live 用两个滑动条分别调整循环的起点与终点,轨道上的圆点显示当前值。
<ClientOnly>
<RenderDemo :loader="cycleLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
需要编排多对象、控制激励源或直接操作单个数值渐变时,继续读[动画曲线](../internals/animation-curves.md)、[动画激励](../internals/animation-excitation.md)、[动画执行器](../internals/animation-runner.md)与[渐变执行器](../internals/animation-transition.md)。
<script setup>
import RenderDemo from '../../.vitepress/components/renderDemo.vue';
const curveModesLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-modes.tsx');
const basicCurvesLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curves-basic.tsx');
const easingCurvesLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curves-easing.tsx');
const specialCurvesLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curves-special.tsx');
const alphaLoader = () =>
import('../../.vitepress/components/demos/ui/animation-alpha.tsx');
const colorLoader = () =>
import('../../.vitepress/components/demos/ui/animation-color.tsx');
const cycleLoader = () =>
import('../../.vitepress/components/demos/ui/animation-cycle.tsx');
</script>
+40 -26
View File
@@ -2,14 +2,15 @@
本指南只讲画屏幕 / 写 UI:怎样用 TSX 画出界面、摆好位置、处理交互、拆成组件,以及 UI 系统与性能的取舍。数据端、存档与录像、插件系统、编辑器等与绘制屏幕关系不紧密的系统不在这里讲,仍见中级 / 高级教程;普通教程只保留主要的渲染逻辑,具体写法集中到本指南。
本指南只收现有 27 篇自定义 UI 文档,不新增系统文档,也不增设系统页面。
本指南只收现有 32 篇自定义 UI 文档,内容分为渲染基础、渲染进阶与渲染底层三层;不新增系统文档,也不增设系统页面。
## 两级结构
## 三级结构
| 分区 | 定位 | 页面数 |
| -------- | -------------------------------------------- | ------ |
| 渲染基础 | 模板、元素、坐标、图形、文字与元素属性 | 10 |
| 渲染进阶 | 响应式、事件、组件化、UI 系统/性能与完整示例 | 17 |
| 分区 | 定位 | 页面数 |
| -------- | ---------------------------------------------- | ------ |
| 渲染基础 | 模板、元素、坐标、图形、文字与元素属性 | 10 |
| 渲染进阶 | 响应式、事件、动画、组件化、UI 系统/性能与示例 | 18 |
| 渲染底层 | 动画曲线、动画激励、执行器与渐变的内部实现 | 4 |
分层是深度标签,不是领域分类:同一层里可能既有元素,也有组件或示例;读到哪一层取决于你要解决的问题,不必按层读完全部页面。
@@ -18,6 +19,8 @@
- **完全没写过 UI**:从 [UI 通用模板(TSX)](./basics/ui-template.md) 起步,先拿模板跑起来,再用 [UI 入门](./basics/ui-basics.md) 认识标签、组件与渲染树。
- **写过基础界面,想加交互与组件**:从[响应式](./advanced/reactivity.md)接手,把状态、事件与条件渲染接进已有界面。
- **想了解 UI 系统与性能**:从 [UI 系统](./advanced/ui-system.md)读起,再看 [UI 性能](./advanced/ui-performance.md)的日常优化习惯。
- **想让界面元素平滑变化**:从[动画](./advanced/animation.md)入手,用 `transitioned`、`transitionedColor` 与 `cycledTransition` 做数值、颜色和循环渐变。
- **想弄清动画曲线与底层怎么推进**:先读[动画曲线](./internals/animation-curves.md),再看[动画激励](./internals/animation-excitation.md)、[动画执行器](./internals/animation-runner.md)与[渐变执行器](./internals/animation-transition.md)。
## 阅读路径
@@ -25,8 +28,9 @@
- **从静态到交互**:[响应式](./advanced/reactivity.md) → [事件与交互](./advanced/events.md) → [条件渲染与循环渲染](./advanced/conditional-and-list-rendering.md) → [按键与快捷键](./advanced/hotkey-in-ui.md) → [什么是组件](./advanced/what-is-component.md) → [自定义组件](./advanced/custom-components.md)。适合界面已经画出来、要接数据和操作的时候。
- **做一个完整面板**:[示例(一)目标与骨架](./advanced/inventory-example-1-skeleton.md) → [示例(二)道具网格](./advanced/inventory-example-2-grid.md) → [示例(三)详情区](./advanced/inventory-example-3-detail.md) → [示例(四)滚动与列表](./advanced/inventory-example-4-scroll.md) → [示例(五)交互与状态](./advanced/inventory-example-5-state.md) → [示例(六)动画、拆分与注册](./advanced/inventory-example-6-animation-and-register.md)。适合把零件装成背包 / 装备面板。
- **改内置 UI 或做性能取舍**:[什么是组件](./advanced/what-is-component.md) → [内置组件:基础](./advanced/builtin-basic.md) → [内置组件:布局](./advanced/builtin-layout.md) → [内置组件:文本](./advanced/builtin-text.md) → [自定义组件](./advanced/custom-components.md) → [UI 系统](./advanced/ui-system.md) → [UI 性能](./advanced/ui-performance.md)。适合替换现成控件或处理缓存与列表开销。
- **让数值与颜色动起来**:[响应式](./advanced/reactivity.md) → [动画](./advanced/animation.md) → 需要更深时读[动画曲线](./internals/animation-curves.md) → [动画激励](./internals/animation-excitation.md) → [动画执行器](./internals/animation-runner.md) / [渐变执行器](./internals/animation-transition.md)。适合给界面加过渡、循环闪烁或颜色变化。
四条路径都建议先读 [UI 通用模板(TSX)](./basics/ui-template.md);模板是后面所有页面的起点。
五条路径都建议先读 [UI 通用模板(TSX)](./basics/ui-template.md);模板是后面所有页面的起点。
## 页面目录
@@ -47,25 +51,35 @@
### 渲染进阶
| 篇目 | 一句话说明 | 前置 |
| -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| [响应式](./advanced/reactivity.md) | 数据变化如何自动推到画布元素,以及渲染函数读到什么才算依赖 | [UI 入门](./basics/ui-basics.md)、[第一个静态界面](./basics/first-static-ui.md) |
| [事件与交互](./advanced/events.md) | 点击、按下、抬起、移动、悬停与滚轮的捕获与冒泡 | [容器与坐标](./basics/container-and-coordinates.md)、[响应式](./advanced/reactivity.md) |
| [条件渲染与循环渲染](./advanced/conditional-and-list-rendering.md) | 用 `hidden` 或三元做条件、用 `.map()` 做循环 | [响应式](./advanced/reactivity.md)、[事件与交互](./advanced/events.md) |
| [按键与快捷键](./advanced/hotkey-in-ui.md) | 按键指令、分组、作用域,以及组件里怎么接 | [响应式](./advanced/reactivity.md)、[事件与交互](./advanced/events.md) |
| [什么是组件](./advanced/what-is-component.md) | 组件最基本的形态、props 的传法,以及组件与 `GameUI` 的关系 | [UI 入门](./basics/ui-basics.md) |
| [内置组件:基础](./advanced/builtin-basic.md) | `Input`、`Icons`、`Arrow`、`Selection`、`Progress`、`Background` 与 `Slider` | [什么是组件](./advanced/what-is-component.md) |
| [内置组件:布局](./advanced/builtin-layout.md) | `Scroll`、`Page`、`List` 与 `ListPage` 的区域与列表用法 | [什么是组件](./advanced/what-is-component.md)、[内置组件:基础](./advanced/builtin-basic.md) |
| [内置组件:文本](./advanced/builtin-text.md) | `TextContent` 的折行与打字机、`ScrollText` 的自动滚动 | [什么是组件](./advanced/what-is-component.md)、[内置组件:基础](./advanced/builtin-basic.md) |
| [自定义组件](./advanced/custom-components.md) | 怎么接收参数、发事件、留出内容位置与透传属性 | [什么是组件](./advanced/what-is-component.md)、[内置组件:基础](./advanced/builtin-basic.md) |
| [UI 系统](./advanced/ui-system.md) | 控制器、实例与栈:打开关闭、隐藏显示与显示策略 | [事件与交互](./advanced/events.md) |
| [UI 性能](./advanced/ui-performance.md) | 一组日常习惯,用来减少不必要的绘制与内存占用 | [层级、变换与性能](./basics/layer-transform-performance.md)、[UI 系统](./advanced/ui-system.md) |
| [示例(一)目标与骨架](./advanced/inventory-example-1-skeleton.md) | 定下背包 / 装备面板的目标、组件拆分与骨架 | [第一个静态界面](./basics/first-static-ui.md)、[容器与坐标](./basics/container-and-coordinates.md) |
| [示例(二)道具网格](./advanced/inventory-example-2-grid.md) | 把道具数据、`ItemCell` 与 `ItemGrid` 填进左侧,让网格能显示与选中 | [示例(一)目标与骨架](./advanced/inventory-example-1-skeleton.md)、[基础图形](./basics/basic-shapes.md) |
| [示例(三)详情区](./advanced/inventory-example-3-detail.md) | 用 `ItemDetail` 填右侧:名称、数量、描述与空选中提示 | [示例(二)道具网格](./advanced/inventory-example-2-grid.md)、[文字](./basics/text.md)、[通用参数](./basics/common-props.md) |
| [示例(四)滚动与列表](./advanced/inventory-example-4-scroll.md) | 把普通网格换成 `Scroll`,并说明渲染树、事件与数据流的变化 | [示例(三)详情区](./advanced/inventory-example-3-detail.md)、[内置组件:布局](./advanced/builtin-layout.md) |
| [示例(五)交互与状态](./advanced/inventory-example-5-state.md) | 加 `ActionBar`:装备、使用、关闭,并把状态收口到面板 | [示例(四)滚动与列表](./advanced/inventory-example-4-scroll.md)、[响应式](./advanced/reactivity.md)、[事件与交互](./advanced/events.md) |
| [示例(六)动画、拆分与注册](./advanced/inventory-example-6-animation-and-register.md) | 让选中态与提示动起来,把代码落回文件并注册成 `GameUI` | [示例(五)交互与状态](./advanced/inventory-example-5-state.md)、[自定义组件](./advanced/custom-components.md)、[UI 系统](./advanced/ui-system.md) |
| 篇目 | 一句话说明 | 前置 |
| -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| [响应式](./advanced/reactivity.md) | 数据变化如何自动推到画布元素,以及渲染函数读到什么才算依赖 | [UI 入门](./basics/ui-basics.md)、[第一个静态界面](./basics/first-static-ui.md) |
| [事件与交互](./advanced/events.md) | 点击、按下、抬起、移动、悬停与滚轮的捕获与冒泡 | [容器与坐标](./basics/container-and-coordinates.md)、[响应式](./advanced/reactivity.md) |
| [条件渲染与循环渲染](./advanced/conditional-and-list-rendering.md) | 用 `hidden` 或三元做条件、用 `.map()` 做循环 | [响应式](./advanced/reactivity.md)、[事件与交互](./advanced/events.md) |
| [按键与快捷键](./advanced/hotkey-in-ui.md) | 按键指令、分组、作用域,以及组件里怎么接 | [响应式](./advanced/reactivity.md)、[事件与交互](./advanced/events.md) |
| [什么是组件](./advanced/what-is-component.md) | 组件最基本的形态、props 的传法,以及组件与 `GameUI` 的关系 | [UI 入门](./basics/ui-basics.md) |
| [内置组件:基础](./advanced/builtin-basic.md) | `Input`、`Icons`、`Arrow`、`Selection`、`Progress`、`Background` 与 `Slider` | [什么是组件](./advanced/what-is-component.md) |
| [内置组件:布局](./advanced/builtin-layout.md) | `Scroll`、`Page`、`List` 与 `ListPage` 的区域与列表用法 | [什么是组件](./advanced/what-is-component.md)、[内置组件:基础](./advanced/builtin-basic.md) |
| [内置组件:文本](./advanced/builtin-text.md) | `TextContent` 的折行与打字机、`ScrollText` 的自动滚动 | [什么是组件](./advanced/what-is-component.md)、[内置组件:基础](./advanced/builtin-basic.md) |
| [自定义组件](./advanced/custom-components.md) | 怎么接收参数、发事件、留出内容位置与透传属性 | [什么是组件](./advanced/what-is-component.md)、[内置组件:基础](./advanced/builtin-basic.md) |
| [动画](./advanced/animation.md) | 用曲线驱动 `transitioned`、`transitionedColor` 与 `cycledTransition`,让数值、颜色平滑变化或循环 | [响应式](./advanced/reactivity.md)、[UI 入门](./basics/ui-basics.md) |
| [UI 系统](./advanced/ui-system.md) | 控制器、实例与栈:打开关闭、隐藏显示与显示策略 | [事件与交互](./advanced/events.md) |
| [UI 性能](./advanced/ui-performance.md) | 一组日常习惯,用来减少不必要的绘制与内存占用 | [层级、变换与性能](./basics/layer-transform-performance.md)、[UI 系统](./advanced/ui-system.md) |
| [示例(一)目标与骨架](./advanced/inventory-example-1-skeleton.md) | 定下背包 / 装备面板的目标、组件拆分与骨架 | [第一个静态界面](./basics/first-static-ui.md)、[容器与坐标](./basics/container-and-coordinates.md) |
| [示例(二)道具网格](./advanced/inventory-example-2-grid.md) | 把道具数据、`ItemCell` 与 `ItemGrid` 填进左侧,让网格能显示与选中 | [示例(一)目标与骨架](./advanced/inventory-example-1-skeleton.md)、[基础图形](./basics/basic-shapes.md) |
| [示例(三)详情区](./advanced/inventory-example-3-detail.md) | 用 `ItemDetail` 填右侧:名称、数量、描述与空选中提示 | [示例(二)道具网格](./advanced/inventory-example-2-grid.md)、[文字](./basics/text.md)、[通用参数](./basics/common-props.md) |
| [示例(四)滚动与列表](./advanced/inventory-example-4-scroll.md) | 把普通网格换成 `Scroll`,并说明渲染树、事件与数据流的变化 | [示例(三)详情区](./advanced/inventory-example-3-detail.md)、[内置组件:布局](./advanced/builtin-layout.md) |
| [示例(五)交互与状态](./advanced/inventory-example-5-state.md) | 加 `ActionBar`:装备、使用、关闭,并把状态收口到面板 | [示例(四)滚动与列表](./advanced/inventory-example-4-scroll.md)、[响应式](./advanced/reactivity.md)、[事件与交互](./advanced/events.md) |
| [示例(六)动画、拆分与注册](./advanced/inventory-example-6-animation-and-register.md) | 让选中态与提示动起来,把代码落回文件并注册成 `GameUI` | [示例(五)交互与状态](./advanced/inventory-example-5-state.md)、[自定义组件](./advanced/custom-components.md)、[UI 系统](./advanced/ui-system.md) |
### 渲染底层
| 篇目 | 一句话说明 | 前置 |
| ------------------------------------------------- | --------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| [动画曲线](./internals/animation-curves.md) | `ExcitationCurve`、`CurveMode`、内置曲线与曲线计算函数 | [动画](./advanced/animation.md)、[响应式](./advanced/reactivity.md) |
| [动画激励](./internals/animation-excitation.md) | 激励源怎样驱动受激励对象,以及变速器与分频器如何接入 | [动画](./advanced/animation.md)、[响应式](./advanced/reactivity.md) |
| [动画执行器](./internals/animation-runner.md) | `Animater` 把多个对象的多个步骤组织成计划组并按时执行 | [动画激励](./internals/animation-excitation.md)、[动画](./advanced/animation.md)、[响应式](./advanced/reactivity.md) |
| [渐变执行器](./internals/animation-transition.md) | `Transition` 让单个数值平滑靠近目标值,处理曲线与结尾参考 | [动画激励](./internals/animation-excitation.md)、[动画](./advanced/animation.md)、[响应式](./advanced/reactivity.md) |
## 边界与注意
@@ -0,0 +1,535 @@
# 动画曲线
曲线把时间进度映射成数据取值:时间完成度从 `0` 走到 `1`,曲线返回一个数,动画系统再用它让数值从起始值逐步走到目标值。本篇是曲线的完整参考:先讲类型与四种模式,再按基础、缓动、双曲三组逐条列出内置曲线,每条曲线都配一个实时曲线图,带参数的曲线还可以在图上调整参数,最后汇总把曲线组合、变换、拼接与多维合并的计算函数。内置形状曲线与分组对照图的纵轴固定为 `0` 到 `1`;运算与变换的实时图按来源与结果的实际输出自适应纵轴范围,不裁剪曲线。高层用法与形状示例见[动画](../advanced/animation.md);单个数值的连续渐变见[渐变执行器](./animation-transition.md)。
## 前置知识
阅读本篇前,建议先读完:
- [动画](../advanced/animation.md)
- [响应式](../advanced/reactivity.md)
## 曲线与数据映射
曲线的类型是 `ExcitationCurve`,它只接收一个时间完成度,返回一个数:
```ts
export type ExcitationCurve = (progress: number) => number;
```
- 输入是时间完成度,范围是 `0` 到 `1`;下面公式里记作 `x`。类型声明里的参数名是 `progress`,两者指同一个值。
- 输出没有范围限制。动画系统不会把它裁剪到 `0` 到 `1`。
- 曲线本身不知道起始值与目标值;它只回答「进度到这里时,映射结果是多少」。把结果用于计算当前值的动作由动画接口或执行器完成。
```ts
import { linear } from '@motajs/animate';
// 匀速曲线:x 为 0.5 时返回 0.5
const curve = linear();
console.log(curve(0.5));
```
## 曲线模式
同一条曲线,换一个模式就会得到不同的快慢分布;先认识这四个模式,后面带 `mode` 参数的曲线才有共同的参照。
`CurveMode` 是曲线的模式枚举,默认值是 `CurveMode.EaseIn`:
```ts
export const enum CurveMode {
/** 缓进快出 */
EaseIn,
/** 快进缓出 */
EaseOut,
/** 缓进缓出,中间快 */
EaseInOut,
/** 快进快出,中间缓 */
EaseCenter
}
```
| 模式 | 含义 | 形状 |
| ---------------------- | ---------------- | ------------------------------ |
| `CurveMode.EaseIn` | 缓进快出 | 从起点慢慢加速,越接近终点越快 |
| `CurveMode.EaseOut` | 快进缓出 | 起步快,接近终点逐渐减速 |
| `CurveMode.EaseInOut` | 缓进缓出,中间快 | 两端慢、中段最快 |
| `CurveMode.EaseCenter` | 快进快出,中间缓 | 两端快、中段最慢 |
### 模式换算
已经有一条按「缓进快出」写好的曲线时,不必为四种模式各写一份;`applyCurveMode` 能在它外面套一层换算,得到新的形状。`applyCurveMode(func, mode)` 接收一条「缓进快出」曲线 $f(x)$,返回套用模式后的新曲线 $g(x)$:
| 模式 | 换算 |
| ------------ | ------------------------------------------------------------------------------------ |
| `EaseIn` | $g(x) = f(x)$ |
| `EaseOut` | $g(x) = 1 - f(1 - x)$ |
| `EaseInOut` | $x < 0.5$ 时 $g(x) = \frac{f(2x)}{2}$;否则 $g(x) = 1 - \frac{f(2 - 2x)}{2}$ |
| `EaseCenter` | $x < 0.5$ 时 $g(x) = \frac{1 - f(1 - 2x)}{2}$;否则 $g(x) = \frac{1 + f(2x - 1)}{2}$ |
```ts
import { applyCurveMode, CurveMode } from '@motajs/animate';
// 把一条缓进快出曲线 f(x) = x^2 换成快进缓出
const easeOut = applyCurveMode((x: number) => x * x, CurveMode.EaseOut);
```
## 基础曲线
基础曲线不接收 `mode` 参数,形状只由自身参数决定。下面每个 live 都使用 `0` 到 `1` 的纵轴。
### 线性曲线 linear()
没有参数,把输入 `x` 原样输出:
$$
f(x) = x,\quad x\in[0,1]
$$
输出始终在 `0` 到 `1`。下面的 live 没有控件,曲线固定为一条直线。
<ClientOnly>
<RenderDemo :loader="linearCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 阶梯曲线 step(k)
参数 `k` 是分段数,取正整数。进度每走 `1/k`,输出跳变一次:
$$
f(x) = \frac{\lfloor x k \rfloor}{k},\quad x\in[0,1]
$$
live 把 `k` 限制在 `2` 到 `12`;`k` 越大,阶梯越细,输出仍在 `0` 到 `1`。
<ClientOnly>
<RenderDemo :loader="stepCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 常数曲线 constant(k)
参数 `k` 是常数值,输出不随进度变化:
$$
f(x) = k,\quad x\in[0,1]
$$
输出始终等于 `k`,可以落在 `0` 到 `1` 之外。live 为了让曲线留在纵轴内,把 `k` 限制在 `0` 到 `1`;调整时看到的仍是同一条水平线。
<ClientOnly>
<RenderDemo :loader="constantCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
## 缓动曲线
缓动曲线以「缓进快出」为基准,接收可选的 `mode`,不传时默认 `CurveMode.EaseIn`。下面给出的是基准形状公式;切换模式后,曲线按上一节的换算改变快慢分布。
### 正弦曲线 sin(mode?)
参数 `mode` 可选,默认 `CurveMode.EaseIn`:
$$
f(x) = 1 - \cos\left(\frac{x\pi}{2}\right),\quad x\in[0,1]
$$
基准形状从 `0` 走到 `1`。live 用四个按钮切换 `CurveMode`,曲线连续变化,可以直接看出快慢分布。
<ClientOnly>
<RenderDemo :loader="sinCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 正切曲线 tan(mode?)
参数 `mode` 可选,默认 `CurveMode.EaseIn`:
$$
f(x) = \tan\left(\frac{x\pi}{4}\right),\quad x\in[0,1]
$$
<ClientOnly>
<RenderDemo :loader="tanCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 正割曲线 sec(mode?)
参数 `mode` 可选,默认 `CurveMode.EaseIn`:
$$
f(x) = \sec\left(\frac{x\pi}{3}\right) - 1,\quad x\in[0,1]
$$
<ClientOnly>
<RenderDemo :loader="secCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 幂曲线 pow(exp, mode?)
`exp` 是指数,必需;`mode` 可选,默认 `CurveMode.EaseIn`。下面公式里把 `exp` 记作 `n`:
$$
f(x) = x^{n},\quad x\in[0,1]
$$
live 把 `exp` 限制在 `0.5` 到 `4`;`exp > 0` 时输出仍在 `0` 到 `1`。
<ClientOnly>
<RenderDemo :loader="powCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
## 双曲曲线
三条双曲曲线同样接收可选的 `mode`,默认 `CurveMode.EaseIn`。`k` 是比例参数。
### 双曲余弦曲线 cosh(k = 2, mode?)
`k` 默认 `2`;`mode` 可选,默认 `CurveMode.EaseIn`:
$$
f(x) = \frac{\cosh(xk) - 1}{\cosh(k) - 1},\quad x\in[0,1]
$$
<ClientOnly>
<RenderDemo :loader="coshCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 双曲正切曲线 tanh(k = 2, mode?)
`k` 默认 `2`;`mode` 可选,默认 `CurveMode.EaseIn`:
$$
f(x) = 1 + \frac{\tanh((x - 1)k)}{\tanh(k)},\quad x\in[0,1]
$$
<ClientOnly>
<RenderDemo :loader="tanhCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 双曲正割曲线 sech(k = 1, mode?)
`k` 默认 `1`;`mode` 可选,默认 `CurveMode.EaseIn`:
$$
f(x) = \frac{1 - \operatorname{sech}(xk)}{1 - \operatorname{sech}(k)},\quad x\in[0,1]
$$
<ClientOnly>
<RenderDemo :loader="sechCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
## 曲线运算
现成曲线不够用时,不必从零写函数:先拿两条曲线做逐点运算,就能拼出叠加、衰减或复合后的形状。这一组函数把两条曲线逐点做运算,返回一条新曲线。下面的实时图里,蓝色与黄色是两条来源曲线,绿色是结果;纵轴按来源与结果的实际输出自适应,超出 `0` 到 `1` 的结果也会完整画出,函数本身不裁剪。
| 函数 | 结果 |
| -------------------------- | -------------------------- |
| `addCurve(curve1, curve2)` | $h(x) = f(x) + g(x)$ |
| `subCurve(curve1, curve2)` | $h(x) = f(x) - g(x)$ |
| `mulCurve(curve1, curve2)` | $h(x) = f(x) \cdot g(x)$ |
| `divCurve(curve1, curve2)` | $h(x) = \frac{f(x)}{g(x)}$ |
| `powCurve(curve1, curve2)` | $h(x) = f(x)^{g(x)}$ |
| `compositeCurve(c1, c2)` | $h(x) = c_1(c_2(x))$ |
`compositeCurve` 是函数复合,`curve1` 是外层、`curve2` 是内层。其余五个函数都按同一进度逐点取值。
```ts
import { addCurve, constant, mulCurve, sin } from '@motajs/animate';
// 在正弦曲线上叠加一个固定偏移,再整体放大
const lifted = addCurve(sin(), constant(0.2));
const doubled = mulCurve(lifted, constant(2));
```
### 相加 addCurve
两条来源曲线逐点相加。结果可能超过 `1`,图中会按实际范围完整显示。
<ClientOnly>
<RenderDemo :loader="addCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 相减 subCurve
第一条曲线减第二条曲线。结果可能低于 `0`,图中同样按实际范围完整显示。
<ClientOnly>
<RenderDemo :loader="subCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 相乘 mulCurve
两条来源曲线逐点相乘。两条来源都落在 `0` 到 `1` 时,结果也落在 `0` 到 `1`。
<ClientOnly>
<RenderDemo :loader="mulCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 相除 divCurve
第一条曲线除以第二条曲线。分母必须避开 `0`,示例用常数 `0.5` 作分母;结果超过 `1` 时按实际范围完整显示。
<ClientOnly>
<RenderDemo :loader="divCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 取幂 powCurve
第一条曲线作底数,第二条曲线作指数。底数保持非负时结果才有实数意义;示例用 `linear()` 作底、常数 `2` 作指数。
<ClientOnly>
<RenderDemo :loader="powCalcLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 复合 compositeCurve
`compositeCurve(curve1, curve2)` 让外层 `curve1` 接收内层 `curve2` 的输出。示例的外层是 `sin()`,内层是 `pow(2)`。
<ClientOnly>
<RenderDemo :loader="compositeCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
## 曲线变换
想保留曲线的基本形状,只把它整体抬高、翻转或压扁时,用这些变换,比重新写一条曲线省事。这一组函数改变一条曲线的整体位置、方向或尺度。下面的实时图按来源与结果的实际输出自适应纵轴范围,不裁剪曲线:
| 函数 | 结果 |
| ----------------------------------- | --------------------------- |
| `moveCurve(curve, move = 0)` | $g(x) = f(x) + move$ |
| `oppositeCurve(curve, move = 0)` | $g(x) = move - f(x)$ |
| `scaleCurve(curve, scale = 1)` | $g(x) = f(x) \cdot scale$ |
| `reciprocalCurve(curve, scale = 1)` | $g(x) = \frac{scale}{f(x)}$ |
此外,`normalize(curve)` 把曲线两端的值对齐到 `0` 与 `1`:
$$
g(x) =
\begin{cases}
\dfrac{f(x) - f(1)}{f(0) - f(1)}, & f(0) > f(1),\\[6pt]
\dfrac{f(x) - f(0)}{f(1) - f(0)}, & f(0) < f(1),\\[6pt]
f(x), & f(0) = f(1).
\end{cases}
$$
它只读 `curve(0)` 与 `curve(1)` 来选择参考端点,假定曲线单调,但不会检查或拒绝非单调曲线。非单调曲线仍按这两个端点归一化,中间取值可能落在 `[0, 1]` 之外;两端相等时原样返回。
### 平移 moveCurve
给来源曲线加一个纵向偏移。结果超过 `1` 时按实际范围完整显示。
<ClientOnly>
<RenderDemo :loader="moveCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 取反 oppositeCurve
以 `move` 为基准翻转来源曲线。`move` 为 `1` 时得到上下翻转、重新落回 `0` 到 `1` 的曲线。
<ClientOnly>
<RenderDemo :loader="oppositeCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 缩放 scaleCurve
纵向缩放来源曲线。`scale` 小于 `1` 时整体压低,结果仍在 `0` 到 `1`。
<ClientOnly>
<RenderDemo :loader="scaleCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 倒数 reciprocalCurve
先取来源曲线的倒数,再乘缩放。来源取值在 `0.5` 到 `1`,避开分母过零;结果落在 `0.5` 到 `1`。
<ClientOnly>
<RenderDemo :loader="reciprocalCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 归一化 normalize
来源取 `0.2` 到 `0.8`,归一化后两端对齐到 `0` 与 `1`。它只用两端值决定方向,假定曲线单调,不会拒绝非单调曲线。
<ClientOnly>
<RenderDemo :loader="normalizeLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
## 曲线拼接
一段动画如果前半段和后半段要用不同节奏,单条曲线表达不了;`sequenceCurve` 能把几条现成曲线按时间比例接起来。`sequenceCurve(seq, duration, scale, move)` 把多条曲线按顺序拼成一条:
- `seq`:曲线数组,按顺序执行。
- `duration`:每段占用的时间比例,范围在 `0` 到 `1` 之间;各段之和通常应设为 `1`。
- `scale`:每段输出在拼接时的缩放比例。
- `move`:每段输出在拼接时的纵向偏移。
```ts
import { linear, sequenceCurve, sin } from '@motajs/animate';
// 参数依次是曲线序列、每段时长占比、每段缩放与每段偏移
const curve = sequenceCurve([linear(), sin()], [0.5, 0.5], [1, 1], [0, 0]);
```
来源段各自都是完整的 `0` 到 `1` 形状,结果按 `duration` 分配的时间段依次取用。下面的实时图把两条来源段都画成完整曲线,绿色结果是两段各占一半时长的拼接结果。
<ClientOnly>
<RenderDemo :loader="sequenceCurveLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
序列过长(超过约 100 段)可能影响性能;需要很多段时,先确认是否可以用公式直接表达。`duration` 之和不为 `1` 时的具体行为不在本篇的保证范围内,需要拼接时按总和 `1` 分配。
## 多维曲线
当一条曲线要同时给出多个分量(例如路径上的横纵坐标),或想把几组一维曲线当成一个整体传递时,就需要多维曲线。多维曲线本质是参数方程:同一个时间完成度同时输出多个值。相关类型有 `ExcitationCurve2D`、`ExcitationCurve3D` 与 `GeneralExcitationCurve`。
拆分把一条多维曲线变成多条一维曲线:
| 函数 | 结果 |
| --------------------- | -------------------------- |
| `splitCurve2D(curve)` | $[c_1(x), c_2(x)]$ |
| `splitCurve3D(curve)` | $[c_1(x), c_2(x), c_3(x)]$ |
| `splitCurve(curve)` | 按维数拆成一维曲线数组 |
合并把多条一维曲线组成一条多维曲线:
| 函数 | 结果 |
| -------------------------------------- | ------------------------------------ |
| `stackCurve2D(curve1, curve2)` | $x \mapsto [c_1(x), c_2(x)]$ |
| `stackCurve3D(curve1, curve2, curve3)` | $x \mapsto [c_1(x), c_2(x), c_3(x)]$ |
| `stackCurve(curves)` | 任意维数的曲线;维数取数组长度 |
```ts
import {
linear,
sin,
splitCurve,
splitCurve2D,
stackCurve2D
} from '@motajs/animate';
// 把一条二维曲线拆成两条一维曲线,再重新合成另一条二维曲线
const [x, y] = splitCurve2D(stackCurve2D(linear(), sin()));
const [backX, backY] = splitCurve(stackCurve2D(x, y));
console.log(backX(0.5), backY(0.5));
```
多维曲线是参数曲线:同一个时间完成度同时给出多个分量,不是一个输入对应一个输出,所以不能画成单张「时间为横轴、单个取值为纵轴」的曲线图。`splitCurve3D` 与 `stackCurve3D` 只是多一维、多一列,`splitCurve` 与 `stackCurve` 则按任意维数处理。
## 边界与注意
- 输出不受 `0` 到 `1` 限制;不要为了「看起来正常」而把结果夹到区间内,否则过冲与回弹会失效。
- `normalize` 只用两端值决定方向,假定曲线单调,但不会检查或拒绝非单调曲线;非单调曲线归一化后,中间取值可能超出 `[0, 1]`。
- `divCurve` 与 `reciprocalCurve` 在分母为 `0` 的位置会产生 `Infinity` 或 `NaN`,组合时要确认除数不会过零。
- `sequenceCurve` 的各段 `duration` 之和通常应设为 `1`;不要依赖总和不为 `1` 时的具体行为。
- 曲线函数应当是纯函数;不要在曲线里读写外部状态,它会在每一帧被反复调用。
<script setup>
import RenderDemo from '../../.vitepress/components/renderDemo.vue';
const linearCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-linear.tsx');
const stepCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-step.tsx');
const constantCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-constant.tsx');
const sinCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-sin.tsx');
const tanCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-tan.tsx');
const secCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-sec.tsx');
const powCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-pow.tsx');
const coshCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-cosh.tsx');
const tanhCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-tanh.tsx');
const sechCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-sech.tsx');
const addCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-calc-add.tsx');
const subCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-calc-sub.tsx');
const mulCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-calc-mul.tsx');
const divCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-calc-div.tsx');
const powCalcLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-calc-pow.tsx');
const compositeCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-calc-composite.tsx');
const moveCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-calc-move.tsx');
const oppositeCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-calc-opposite.tsx');
const scaleCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-calc-scale.tsx');
const reciprocalCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-calc-reciprocal.tsx');
const normalizeLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-calc-normalize.tsx');
const sequenceCurveLoader = () =>
import('../../.vitepress/components/demos/ui/animation-curve-calc-sequence.tsx');
</script>
@@ -0,0 +1,344 @@
# 动画激励
动画不会自己动:需要有人按节奏推一下。动画激励把这件事拆成两半——激励源决定什么时候推,受激励对象决定被推时做什么。动画执行器与渐变执行器都是受激励对象,所以能挂在同一个激励源上。
本篇按「受激励对象是什么、激励源是什么、四种内置激励源怎么用、组件里怎么接」的顺序讲。变速器与分频器本身也是激励源,会放在内置激励源里一起说明。
## 前置知识
阅读本篇前,建议先读完:
- [动画](../advanced/animation.md)
- [响应式](../advanced/reactivity.md)
## 激励模型
系统里有三个角色:
| 角色 | 是什么 | 负责 |
| ------------------------- | ---------------------- | -------------------------------------- |
| `IExcitable<T>` | 受激励对象 | 接收一次负载,执行自己的处理 |
| `IExcitation<T>` | 激励源 | 决定什么时候推进,并管理所有受激励对象 |
| `IExcitableController<T>` | 单个受激励对象的控制器 | 解除这次登记,或手动推进这一个对象 |
「激励」就是按节奏推进一次:激励源把当前的负载交给每个登记过的对象。负载的类型由具体激励源决定;动画系统里的激励源都传数字时间,所以执行器接收的是 `number`。
激励源不关心对象是动画、渐变还是普通回调;动画执行器与渐变执行器都是 `IExcitable<number>`,所以能挂在同一个激励源上。
```mermaid
flowchart LR
S[激励源] -->|负载| A[受激励对象 A]
S -->|负载| B[受激励对象 B]
S -->|add| C[控制器] -->|revoke| S
```
当一个激励源把另一个激励源当作时间来源时,本篇把前者叫 **输入源**,把登记在它上面、接收它推进的对象叫 **接收方**。例如变速器从输入源读取时间,再把换算后的时间交给接收方。
## 受激励对象
`IExcitable<T>` 不需要继承任何类,也没有别的成员;它只要求一个具体方法 `excited(payload: T): void`。激励源每次推进时调用这个方法,`payload` 就是这次传来的负载。
```ts
import { IExcitable } from '@motajs/animate';
// 受激励对象:每次被推进时记下负载
class TimeRecorder implements IExcitable<number> {
last = 0;
excited(payload: number): void {
this.last = payload;
}
}
```
要让激励源每次推进都通知它,需要把它登记进去。`add` 返回一个控制器;控制器只管理这一个对象,不影响同一个源上的其他接收方:
```ts
import { RafExcitation } from '@motajs/animate';
const source = new RafExcitation();
const recorder = new TimeRecorder();
// 登记后,源每推进一次,recorder 就收到一次时间
const controller = source.add(recorder);
// 只推进 recorder 一个对象,不广播给其他接收方
controller?.excite(source.payload());
// 解除登记;之后源不会再推进这个对象
controller?.revoke();
```
`IExcitableController<T>` 就是 `add` 返回的控制器,包含三个成员:
- `excitable`:被登记的那个对象。
- `revoke()`:把对象从当前激励源移除。
- `excite(payload)`:只推进这一个对象,不广播给其他对象。
### 包装函数 excited
如果手上只有一段函数,不想为它单独写一个类,`excited(func, thisArg?)` 可以把它包成 `IExcitable<T>`:
```ts
import { excited } from '@motajs/animate';
// 把函数包成受激励对象;每次激励时函数收到负载
const recorder = excited<number>(payload => {
console.log(payload);
});
```
它返回的对象只有一个 `excited` 方法:每次激励源推进时调用 `func(payload)`,不会替调用方保存状态。包装后的对象可以直接交给 `add`、`onExcited` 等接收 `IExcitable<T>` 的地方。
包装只提供 `excited`,不提供 `revoke` 或 `excite`;要解除登记或单独推进,仍然使用 `add` 返回的控制器。需要保存状态、读取上一次负载或提供多个方法时,写一个实现 `IExcitable<T>` 的类更清楚。
`thisArg` 可选,用来固定 `func` 执行时的 `this`;省略时函数按原来的方式调用。
## 激励源接口
自带激励源之外,有时需要替换节奏或自己实现一个。无论哪种,都要满足同一套契约;内置激励源已经实现好,只有自己写源时才需要逐项实现。
| 成员 | 作用 |
| ----------------- | ----------------------------------------------------- |
| `payload()` | 读取当前负载 |
| `excite(payload)` | 把负载广播给当前所有受激励对象 |
| `add(object)` | 登记一个受激励对象,返回控制器;无法登记时返回 `null` |
| `remove(object)` | 移除一个受激励对象,返回是否移除成功 |
| `destroy()` | 终止激励源,停止继续推进 |
`payload()` 回答「现在的时间或值是多少」,`excite()` 回答「把这一刻发给谁」。帧激励源每帧更新当前时间后调用一次 `excite()`;固定间隔激励源按定时器调用;变速器与分频器则在收到输入源的推进后,按自己的规则再推进接收方。
## 内置激励源
内置激励源分两类:帧激励源与固定间隔激励源负责产生时间,变速器与分频器负责加工另一个激励源的时间或次数。下面每个都先说为什么需要,再给一段最小用法,最后说明接收方会收到什么。
### 帧激励源
界面动画通常希望跟着屏幕刷新走;帧激励源就是这条默认节奏,根渲染器默认也用它。
`RafExcitation` 用 `requestAnimationFrame` 驱动,每一帧把当前时间戳作为负载广播出去。它最直接的用法是接到动画执行器上:
```ts
import { Animater, RafExcitation } from '@motajs/animate';
const source = new RafExcitation();
const animater = new Animater();
// 把执行器登记到帧激励源;之后执行器每帧被推进一次
source.add(animater);
```
接收方拿到的负载是 `requestAnimationFrame` 的时间戳,单位毫秒,例如 `1234.5`。它不是从 `0` 开始的动画时间,而是浏览器给这一帧的时间;相邻两帧的差值反映这一帧间隔了多久。
- `payload()` 返回最近一帧的时间戳。
- 构造时立即开始请求下一帧,所以第一次推进发生在下一帧,不是构造的瞬间。
- `destroy()` 取消尚未执行的帧请求。
渲染器的根元素默认使用一个 `RafExcitation`,所以组件里拿到的动画执行器通常不需要自己创建激励源。
下面的 live 显示当前载荷、相邻两帧的时间差与已过的帧数。
<ClientOnly>
<RenderDemo :loader="rafPayloadLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 固定间隔激励源
有些逻辑只需要稳定节奏,不必跟屏幕刷新同步;固定间隔激励源按定时器推进,节奏由构造时传入的间隔决定。
`IntervalExcitation` 实现 `IIntervalExcitation`,用固定毫秒间隔触发。登记一个接收方后,它会按间隔反复推进:
```ts
import { IntervalExcitation } from '@motajs/animate';
const source = new IntervalExcitation(100);
// 复用前面的 TimeRecorder
const recorder = new TimeRecorder();
// 约每 100ms 推进一次;接收方依次收到 0、100、200……
source.add(recorder);
```
它用内部计数当负载:触发时先把当前计数发出去,再把计数加一个 `interval`。所以接收方依次拿到 `0`、`interval`、`2 × interval`……;`payload()` 返回计数器的当前值,第一次触发后它已经变成 `interval`。
这个计数不跟随真实时间(墙钟时间),也不保证每一次都恰好落在整百毫秒上。需要和真实时间对齐时,使用帧激励源。
### 变速器
需要整体放慢、加速,或让速度平滑变化时,不必改每个动画的时长;把变速器接在一个激励源后面,就能统一改变时间流速。
`ExcitationVariator` 实现 `IExcitationVariator`,本身就是一种 `IExcitation<number>`。它先订阅一个输入源,再把输入时间按当前速度换算成自己的时间,最后用自己的时间推进接收方。
```ts
import { Animater, ExcitationVariator, RafExcitation } from '@motajs/animate';
const input = new RafExcitation();
const variator = new ExcitationVariator();
const animater = new Animater();
// 以帧激励源为输入源;绑定后速度重置为 1
variator.bindExcitation(input);
// 执行器登记在变速器上,收到的是变速器换算后的时间
variator.add(animater);
// 输入时间每前进 10ms,执行器只前进 5ms
variator.setSpeed(0.5);
```
接收方拿到的是变速器时间轴上的时间,不是输入源的原始时间。绑定时它从输入源当前时间起步;之后每次输入推进,它把「输入前进了多少」乘以当前速度,累加到自己的时间上,再发给接收方。`payload()` 返回这个时间。
速度改变的是时间流速,不是动画配置里的时长。一个动画在变速器时间轴上配置为 `400`,速度设为 `0.5` 后,它仍然需要变速器时间轴前进 `400`;只是这段变速器时间现在要用两倍的真实时间才能走完。改变速度不会重算已经过去的时间,只影响之后的推进。
`setSpeed` 必须放在 `bindExcitation` 之后:未绑定时它不会生效。绑定时速度会重置为 `1`,所以先绑定、再设置速度。
下面的 live 显示输出端连续两次时间的差值。切换速度后,相邻两次推进的时间差会随之改变。
<ClientOnly>
<RenderDemo :loader="variatorLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 变速曲线
直接改速度会让时间流速瞬间跳变;需要慢慢加速或减速时,用 `curveSpeed` 在一段时间内按曲线改变速度。
`curveSpeed(curve, time, mode?)` 让速度在 `time` 毫秒内按曲线变化,返回一个 Promise,在曲线结束时兑现。已经有一条曲线在运行时,新曲线会排在它后面。
```ts
import { linear } from '@motajs/animate';
// 在输入源时间 300ms 内,速度从 1 线性降到 0.5
await variator.curveSpeed(x => 1 - 0.5 * x, 300);
```
曲线的输入是这段时间的完成度,输出就是当前速度。第三个参数 `VariatorCurveMode` 决定曲线进度按哪条时间轴计算:
| 模式 | 曲线进度按谁走 |
| --------------------------------- | ---------------------------------------------- |
| `VariatorCurveMode.SourceRelated` | 按输入源的时间走,速度变慢不会拖慢曲线本身 |
| `VariatorCurveMode.SelfRelated` | 按变速器自己的时间走,速度变慢时曲线也一起变慢 |
默认是 `SourceRelated`。
下面的 live 用一条从 `1.5` 降到 `0.25` 的变速曲线演示这一点。它显示当前速度、输出端最后两次推进的时间,以及两者的时间差。速度越高,输出端时间推进越快,相邻两次推进的时间差也越大。
<ClientOnly>
<RenderDemo :loader="curveSpeedLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 分频器
不是每一次激励都需要处理,例如只需要低频刷新的逻辑;分频器把输入源的多次激励压成一次,减少接收方的更新次数。
`ExcitationDivider<T>` 实现 `IExcitationDivider<T>`,也是 `IExcitation<T>`。它接收输入源的每一次推进,但只把其中一部分继续发给接收方。
```ts
import { ExcitationDivider, IntervalExcitation } from '@motajs/animate';
const input = new IntervalExcitation(100);
const divider = new ExcitationDivider<number>();
// 复用前面的 TimeRecorder
const recorder = new TimeRecorder();
// 绑定后分频比为 1,输入推进一次就转发一次
divider.bindExcitation(input);
divider.add(recorder);
// 之后输入每推进 3 次,接收方收到 1 次
divider.setDivider(3);
```
接收方收到的负载仍是输入源传来的那一份,只是有些推进被丢掉了。`payload()` 返回最近一次转发出去的负载;从未绑定输入源时读取它会报错。
分频器改变的是激励次数,不是时间速度。它不能用来让动画整体变慢——那应该使用变速器。`setDivider` 可以在绑定后调用;未绑定时调用不会生效,也不会报错。
`divider` 是当前分频比例,默认 `1`。设置后,下一次输入推进会立即转发一次,之后每隔 `divider` 次输入推进再转发一次。
下面的 live 用固定间隔激励源驱动分频器:左侧是输入源的原始载荷与次数,右侧是接收方实际收到的载荷与次数。改变分频比后,接收方次数按比例减少,但收到的载荷仍是输入源传来的那一份。
<ClientOnly>
<RenderDemo :loader="dividerLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
## 组件内的激励接入
渲染端把整块 UI 挂在一棵渲染树上,树的最顶层叫根渲染器;它自带一个激励源。渲染端还提供了两个组件内辅助函数,用来把每帧逻辑挂到根渲染器的激励源上。
### 登记受激励对象 onExcited
已经有一个 `IExcitable<number>`,又希望它跟着根渲染器的激励源每帧推进时,用 `onExcited`。手动 `add` 到根激励源也能做到,但组件卸载时容易漏掉移除,留下泄漏;这个函数把登记与清理放在一起。
`onExcited(excitable: IExcitable<number>): void` 接收一个受激励对象,不接收函数。它只能在组件的 `setup` 或生命周期钩子中调用;在组件外调用不会生效。
```ts
import { onExcited } from '@motajs/render-vue';
// 复用前面的 TimeRecorder
const recorder = new TimeRecorder();
// 只在组件 setup 或生命周期钩子中调用
onExcited(recorder);
```
调用后,根渲染器每帧推进时 `recorder.excited(time)` 会收到当前帧的时间戳。它返回 `void`,没有可操作的控制器;组件卸载时会自动移除登记,根渲染器变化时也会在新根上重新登记。不要在组件外使用它,也不要在卸载后继续依赖这个登记。
### 包装函数 onExcitedFunc
每帧逻辑如果只是一段函数,不想先写一个 `IExcitable` 类,用 `onExcitedFunc`。它把函数包成受激励对象再登记,省掉手工包装。
`onExcitedFunc(func: (time: number) => void): void` 接收一个每帧调用的函数,参数是根渲染器当前帧的时间戳。它同样只能在组件的 `setup` 或生命周期钩子中调用;在组件外调用不会生效。
```ts
import { onExcitedFunc } from '@motajs/render-vue';
let elapsed = 0;
// 只在组件 setup 或生命周期钩子中调用
onExcitedFunc(time => {
// time 是根渲染器当前帧的时间戳
elapsed = time;
});
```
它内部用 `excited(func)` 包装后交给 `onExcited`,所以清理行为与 `onExcited` 相同:组件卸载时自动移除登记,根渲染器变化时重新登记。包装后的对象不保存状态;需要读取上一次负载或提供多个方法时,仍然写一个实现 `IExcitable<number>` 的对象,再用 `onExcited` 登记。
## 与两个执行器的关系
`Animater` 与 `Transition` 都实现 `IExcitable<number>`,因此:
- 它们可以绑定任意数字激励源,包括 `RafExcitation`、`IntervalExcitation`、`ExcitationVariator` 与 `ExcitationDivider`。
- 变速器与分频器也是激励源,可以接在执行器前面,分别改变时间流速与激励次数。
高层封装如 `transitioned`、`transitionedColor` 与 `cycledTransition` 也共享同一套根激励源,因此不需要再单独创建时钟。
## 边界与注意
- 变速器与分频器都要先绑定输入源才能工作;变速器未绑定时 `setSpeed` 不生效,分频器从未绑定输入源时读取 `payload()` 会报错。
- 变速器绑定输入源时会把速度重置为 `1`,并把自己的时间对齐到输入源的当前时间;需要别的速度就在绑定之后设置。
- `onExcited` 与 `onExcitedFunc` 只适用于组件内部;组件外要自己创建 `IExcitable` 并手动登记、移除。
- 变速器改变的是时间流速,分频器改变的是激励次数;用分频器让动画变慢会跳过中间帧,不会拉长动画时间。
<script setup>
import RenderDemo from '../../.vitepress/components/renderDemo.vue';
const rafPayloadLoader = () =>
import('../../.vitepress/components/demos/ui/excitation-raf-payload.tsx');
const variatorLoader = () =>
import('../../.vitepress/components/demos/ui/excitation-variator.tsx');
const dividerLoader = () =>
import('../../.vitepress/components/demos/ui/excitation-divider.tsx');
const curveSpeedLoader = () =>
import('../../.vitepress/components/demos/ui/excitation-curve-speed.tsx');
</script>
@@ -0,0 +1,570 @@
# 动画执行器
动画执行器 `Animater` 实现 `IAnimater`,负责把多个动画对象的多个步骤组织成一条时间线。它关心的是「谁在第几步动、下一步什么时候开始」,而不是单个数值的平滑过渡;一个数从当前值靠近目标值,用[渐变执行器](./animation-transition.md)。
## 前置知识
阅读本篇前,建议先读完:
- [动画曲线](./animation-curves.md)
- [动画激励](./animation-excitation.md)
- [动画](../advanced/animation.md)
- [响应式](../advanced/reactivity.md)
## 获取执行器与激励接入
执行器自己不产生时间:它只接收外部传来的时间戳,再据此推进计划。推动它的对象叫**激励源**:例如 `RafExcitation` 每帧把当前时间戳推给执行器一次。没有接上激励源时,计划可以写好,但一步都不会执行。所以动手编排之前,先要知道执行器从哪里来、怎样接上时间。
### 组件内获取
组件里通常不自己创建执行器:手写 `new` 既要记得绑定激励源,又容易在组件卸载后继续持有。`useAnimater(anim?, excitation?)` 返回 `IAnimater | null`,只能在组件的 `setup` 或生命周期钩子中调用;它默认把执行器接到根渲染器的激励源上,根渲染器变化时重新绑定,组件卸载时解除绑定。
不传执行器时,它内部新建一个,并在卸载时一并销毁;传入已有执行器时,只负责绑定与解绑,执行器仍由调用方持有。需要显式指定激励源时,传第二个参数。使用 `useAnimater` 时,不需要自己调用 `destroy()`。
```ts
import { ref } from 'vue';
import { useAnimater } from '@motajs/render-vue';
const x = ref(0);
// 只能在组件 setup 或生命周期钩子中调用;
// 它绑定根渲染器的激励源,并在组件卸载时自动解绑。
const animater = useAnimater()!; // 尚无当前对象;尚无步骤;取得执行器
```
### 手动创建
不在组件里时,`useAnimater` 会返回 `null`,这时可以自己 `new Animater()`。它可以在普通 JavaScript 允许的任何位置创建;但执行器不会自己找时间,必须由你调用 `bindExcitation(excitation)` 把它接到一个数字激励源上。之后用 `unbindExcitation()` 解除绑定,也可以再接到别的源。
手动创建的执行器由调用方负责生命周期。需要停止并重置时调用 `destroy()`:它会解绑激励源,并清掉已定义与正在执行的计划。这个清理是手动创建的场景才需要的;使用 `useAnimater` 时,卸载清理已经由它完成。
```ts
import { Animater, RafExcitation } from '@motajs/animate';
const excitation = new RafExcitation(); // 尚无当前对象;尚无步骤;创建激励源
// 可在普通 JS 中创建;执行器不会自己找时间。
const animater = new Animater(); // 尚无当前对象;尚无步骤;创建执行器
// 必须自己绑定激励源;不绑定就不会推进。
animater.bindExcitation(excitation); // 尚无当前对象;尚无步骤;绑定执行器自己的激励源
// 不再需要推进时解绑;之后可以重新绑定。
animater.unbindExcitation(); // 尚无当前对象;尚无步骤;解绑激励源
```
两种方式绑定的不是同一个激励源:`useAnimater` 默认绑根渲染器的激励源;`new Animater` 绑你传给 `bindExcitation` 的那个源。重复绑定同一个源不会重复登记。
## 计划模型
动画是某个可写数值从当前值走向目标值的一段过程。一次动画至少要回答三件事:哪个数值、走向哪个目标、用多久;曲线决定这段时间里快慢怎么变。
定义动画就是把这几项信息写进一条时间线:先确定动画对象,再确定曲线,然后写步骤。步骤只记录意图,不会立刻修改对象的数值;提交整组之前,数值保持原样。
每个步骤都有开始与结束两个时刻,后续步骤可以挂在其中一个时刻上,再等待若干毫秒。挂在开始时刻上的称为**开始触发**,挂在结束时刻上的称为**结束触发**;触发点上可以继续挂步骤,于是形成顺序、延迟与重叠。
- **并行**:同一组里没有挂到任何触发点上的步骤,会随组开始一起启动。
- **顺序**:把后一段挂到前一段的结束触发上;前一段结束、等待一段时间后,后一段才开始。
- **延迟与重叠**:把后一段挂到前一段的开始触发上;前一段开始、等待一段时间后,后一段就启动。结束触发等待 `0` 表示紧接着开始,开始触发等待 `0` 表示同时开始。
- **计划组**:一次提交的步骤集合是一组。组与组之间串行:后一组要等前一组的全部步骤、以及这些步骤上的触发点都结束,再经过组后等待,才真正开始。组内可以并行,组间不重叠。
- **等待点**:每个步骤结束时会兑现一个完成信号;也可以按组内编号查到某个步骤的目标值、时长、曲线和完成信号,再等待它。完成信号只代表这个步骤结束,不代表整组结束。
下面的 live 用真实执行器播放一组计划:上方是对象 A 与 B 的当前值,下方色块是步骤段,竖线是播放头。播放头本身也是一条同组同时长的步骤,不是页面定时器。
<ClientOnly>
<RenderDemo :loader="timelineLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
## 动画对象的选择
为了让动画系统知道它该如何执行动画、将当前值写入哪个对象,就必须先使用 `animate` 接口来绑定动画对象。`animate(content: IAnimatable): this` 选中的对象必须满足 `IAnimatable`:一个带可写 `value` 的对象;Vue 的 `ref<number>` 就满足这个形状。执行器只改这个字段,不负责把值画到画布。
`animate` 只改变「之后的操作作用在谁身上」,本身不新增步骤,也不移动任何值。同一个对象在一个计划组里可以多次出现,它的步骤编号会继续累加。没有先选对象就调用 `to` 时,执行器不会添加任何步骤——计划看起来写了,实际不会动,所以选择对象要放在写步骤之前。
```ts
import { ref } from 'vue';
import { useAnimater } from '@motajs/render-vue';
const x = ref(0);
const animater = useAnimater()!;
animater.animate(x); // 当前对象:x;尚无步骤;选择 x 作为动画对象
```
## 曲线
一条步骤只知道从当前值走向目标值、用多久;如果不再说明过程中的快慢,系统只能用匀速。`curve(curve: ExcitationCurve): this` 就是为此设置速率曲线的。`ExcitationCurve` 是 `(progress: number) => number`,把 `0`–`1` 的时间进度映射成一个数;不设置时使用线性曲线。
时间进度从 `0` 走到 `1`。曲线在当前进度下的返回值表示此时刻动画的完成度:为 `0` 时动画处于起点,为 `1` 时刚好执行到目标值,中间按曲线返回的比例推进。曲线返回值超出 `0` 到 `1` 时,值会越过目标或朝反方向走。
曲线在定义步骤时记入步骤,之后再改 `curve` 不会影响已经定义好的步骤。它会一直作用于后续步骤,直到再次调用 `curve`;`planEnd` 不会把它恢复成线性。
```ts
import { sin } from '@motajs/animate';
const x = ref(0);
animater
.animate(x) // 当前对象:x;尚无步骤;选择 x
.curve(sin()) // 当前对象:x;尚无步骤;设置当前曲线
.to(1, 400) // 当前对象:x;新增索引 1;写入步骤
.planEnd(); // 当前对象:x;索引 1;结束本组,当前对象清空
```
## 步骤与终值
计划模型与选好的对象还只是准备,要真正让某个值动起来,必须追加一条具体步骤:从当前值走到哪个目标值、用多久。`to(value: number, time: number, end: EndRelation = EndRelation.Target): this` 就是用来追加这条步骤的。不调用 `to`,再完整的模型也不会产生动画。
`value` 是目标值,`time` 是时长(毫秒),`end` 是结束参考方式。调用 `to` 只把步骤写进当前组,不会立刻修改动画对象的值;要等组开始并执行到这一步时才生效。如果当前正挂着开始触发或结束触发,这条步骤会挂到触发点,而不是随组开始;没有触发点时,它才是组启动步骤。
`EndRelation` 决定动画结束时把值写成什么:
| 结尾参考 | 动画结束时的值 |
| -------------------- | -------------------------------------------------- |
| `EndRelation.Target` | 直接写成传入的目标值 |
| `EndRelation.Curve` | 停在曲线终点;不一定等于目标值 |
| `EndRelation.Self` | 正常结束时同 `Curve`;提前结束时停在接管那一刻的值 |
默认是 `EndRelation.Target`。使用 `Curve` 时,如果曲线在终点不回到目标值,对象最终会停在另一个值;终点由曲线在 `1` 处的输出决定。
```ts
import { sin } from '@motajs/animate';
const x = ref(0);
animater
.animate(x) // 当前对象:x;尚无步骤;选择 x
.curve(sin()) // 当前对象:x;尚无步骤;设置当前曲线
.to(100, 400, EndRelation.Curve) // 当前对象:x;新增索引 1;写入步骤,结尾按曲线终点
.planEnd(); // 当前对象:x;索引 1;结束本组,当前对象清空
```
## 结束触发
组内步骤默认一起开始;如果希望后一段等前一段真正结束再开始,就需要把后一段挂到前一段的结束时刻上。`after(time = 0): this` 做这件事:它把后续步骤挂到上一次定义的步骤结束之后,再等待 `time` 毫秒。没有它,两段只能并行,或者靠猜时长来凑先后。
`after` 锚定的是上一次定义的步骤,不是当前 `animate` 选中的对象;如果还没有任何步骤,它不会建立关联。把 `after` 直接写在它要锚定的 `to` 后面,再选下一个对象,读起来就是「这段结束后,再让谁动」:
```ts
const x = ref(0);
const y = ref(0);
animater
.animate(x) // 当前对象:x;尚无步骤;选择 x
.to(1, 400) // 当前对象:x;新增索引 1;写入步骤
.after(120) // 当前对象:x;索引 1;把后续步骤挂到索引 1 结束之后,等待 120ms
.animate(y) // 当前对象:y;尚无步骤;选择 y
.to(1, 150) // 当前对象:y;新增索引 1;写入步骤(挂到 x 索引 1 结束之后)
.planEnd(); // 当前对象:y;索引 1;结束本组,当前对象清空
```
`after` 只能锚定上一条定义的步骤;要挂在组里其它对象、其它编号的步骤之后,就需要按对象与编号指定。`afterPlan(content: IAnimatable, index: number, time = 0): this` 就是为此把后续步骤挂到当前计划组里指定对象、指定索引的步骤结束之后。`index` 从 `1` 开始;找不到对应步骤时不会建立这个关联,若之前已经挂过触发,基准保持原样,否则后续步骤随组开始。
```ts
animater
.animate(x) // 当前对象:x;尚无步骤;选择 x
.to(100, 200) // 当前对象:x;新增索引 1;写入步骤
.afterPlan(x, 1, 50) // 当前对象:x;索引 1;把后续步骤挂到 x 索引 1 结束之后,等待 50ms
.animate(y) // 当前对象:y;尚无步骤;选择 y
.to(50, 150) // 当前对象:y;新增索引 1;写入步骤(挂到 x 索引 1 结束之后)
.planEnd(); // 当前对象:y;索引 1;结束本组,当前对象清空
```
调用 `after` 或 `afterPlan` 之后,后续的步骤会继续挂到同一个基准上,直到下一次 `after`、`when` 或 `planEnd` 改变它。两者都只能引用当前正在定义的组;已经封口的组不能再被挂触发点。
## 开始触发
结束触发只能让两段首尾相接;若希望后一段在前一段开始后某个时刻就启动,让两段重叠,就需要以开始时刻为基准。`when(time = 0): this` 把后续步骤挂到上一次定义的步骤开始时刻之后,再等待 `time` 毫秒。没有它,两段要么完全同时开始,要么等前一段结束。
```ts
animater
.animate(x) // 当前对象:x;尚无步骤;选择 x
.to(1, 400) // 当前对象:x;新增索引 1;写入步骤
.when(100) // 当前对象:x;索引 1;把后续步骤挂到索引 1 开始之后,等待 100ms
.animate(y) // 当前对象:y;尚无步骤;选择 y
.to(1, 150) // 当前对象:y;新增索引 1;写入步骤(挂到 x 索引 1 开始之后)
.planEnd(); // 当前对象:y;索引 1;结束本组,当前对象清空
```
`when` 也只能锚定上一条定义的步骤;要以后面组里任意一条已有步骤的开始时刻为基准,就需要按对象与编号指定。`whenPlan(content: IAnimatable, index: number, time = 0): this` 就是为此以当前计划组里指定对象、指定索引的步骤为基准,从它开始执行的时刻起等待 `time` 毫秒。写法与 `afterPlan` 相同,只是基准从「步骤结束」改为「步骤开始」。
```ts
animater
.animate(x) // 当前对象:x;尚无步骤;选择 x
.to(1, 500) // 当前对象:x;新增索引 1;写入步骤
.whenPlan(x, 1, 200) // 当前对象:x;索引 1;把后续步骤挂到 x 索引 1 开始之后,等待 200ms
.animate(y) // 当前对象:y;尚无步骤;选择 y
.to(1, 200) // 当前对象:y;新增索引 1;写入步骤(挂到 x 索引 1 开始之后)
.planEnd(); // 当前对象:y;索引 1;结束本组,当前对象清空
```
`when` 与 `after` 都锚定上一次定义的步骤,所以调用顺序会影响挂载点:先 `animate(y)` 不会改变锚点,紧接着的 `when` 或 `after` 仍然挂在 `x` 的上一条步骤上。把触发写在锚点步骤之后,可以少一次回头确认。
## 查询与等待
计划提交后,代码有时需要读出某一步的目标值与时长。`query(content: IAnimatable, index: number, plan?: number): IAnimationPlan | null` 就是为此查询步骤的;没有它,只能自己记住定义时写了什么,或者等整组结束后再回头找。
另一些时候,代码只想等某一步完成再继续,而不想等整组结束。`wait(content: IAnimatable, index: number, plan?: number): Promise<void>` 就是为此等待单个步骤的;没有它,只能猜时长,或者在组尾统一处理。
`index` 是该对象在本计划组里的步骤编号,从 `1` 开始;`plan` 是计划组索引,由 `planEnd` 返回。省略 `plan` 时,`query` 查询当前正在定义中的组;`planEnd` 之后当前组已经封口,要查已定义的组必须显式传入组索引。`wait` 省略 `plan` 时先找当前正在执行的组;没有执行中的组时,按当前正在定义中的组查找。步骤不存在时立即兑现,步骤存在时只等这一条结束,不等整组。步骤被后续步骤接管时,它的完成信号也会兑现。
`IAnimationPlan` 的常用成员:
| 成员 | 含义 |
| ------------- | -------------------------------- |
| `identifier` | 动画对象与组内步骤编号 |
| `curve` | 这个步骤的速率曲线 |
| `targetValue` | 目标值 |
| `time` | 动画时长 |
| `promise` | 这个步骤执行完毕后兑现的 Promise |
```ts
const x = ref(0);
const group = animater
.animate(x) // 当前对象:x;尚无步骤;选择 x
.to(100, 300) // 当前对象:x;新增索引 1;写入步骤
.after(100) // 当前对象:x;索引 1;把后续步骤挂到索引 1 结束之后,等待 100ms
.to(200, 200) // 当前对象:x;新增索引 2;写入步骤(挂到索引 1 结束之后)
.planEnd(); // 当前对象:x;索引 2;结束本组,当前对象清空
const second = animater.query(x, 2, group); // 当前对象:无;组 group 索引 2;读取 x 的步骤
// second?.targetValue 为 200
await animater.wait(x, 2, group); // 当前对象:无;组 group 索引 2;等待 x
```
`query` 与 `wait` 的默认范围不同:`query` 默认查当前正在定义的组,`wait` 默认查当前正在执行的组。定义完计划后要查询该组,通常显式传入 `planEnd` 的返回值。
## 计划组收尾
写步骤时,系统需要一个明确边界知道「这一组到这里定义完毕」,并据此决定什么时候开始执行、组前与组后各等多久、下一组怎样排队;`planEnd(preTime = 0, postTime = 0): number` 就是这条边界。不调用它,当前组不会提交,后续步骤会继续累积在同一组里,也不会开始执行。
`planEnd` 什么时候调用由你决定:在关闭它之前,当前组一直保持「定义中」,可以继续用 `to` 往里加步骤。它不需要在写完第一条步骤后立刻调用;但组只有在 `planEnd` 之后才会被排队执行。
`planEnd` 返回组索引,从 `1` 开始;没有定义任何步骤时返回 `-1`。
- `preTime` 是组执行前的等待时长(毫秒),等待结束后才开始组内第一批步骤。
- `postTime` 是组执行后的等待时长(毫秒),组内步骤、开始触发与结束触发全部结束后再等待这么久,计划组才真正结束。
- 后一个计划组会等前一个计划组全部结束之后才开始,因此组与组之间不会重叠。
```ts
const x = ref(0);
const y = ref(0);
// 第一个计划组:x 与 y 同时走向各自目标
animater
.animate(x) // 当前对象:x;尚无步骤;选择 x
.to(100, 300) // 当前对象:x;新增索引 1;写入步骤
.animate(y) // 当前对象:y;尚无步骤;选择 y
.to(50, 300) // 当前对象:y;新增索引 1;写入步骤(随组开始,与 x 并行)
.planEnd(); // 当前对象:y;索引 1;结束组 1,当前对象清空
// 第二个计划组:等第一个组全部结束后,x 再回到 0
animater
.animate(x) // 当前对象:x;新组重新计数,尚无步骤;选择 x
.to(0, 200) // 当前对象:x;新增索引 1;写入步骤
.planEnd(); // 当前对象:x;索引 1;结束组 2,当前对象清空
```
## 执行器状态与读取规则
把上面的操作放在一起看,`Animater` 是一台按状态工作的执行器:它记住当前选中的对象、当前曲线、触发基准,以及正在定义或执行的计划组。每个接口只读写其中一部分状态;理解这一点,才能判断一行代码在看谁、写谁。
| 操作 | 读取的状态 | 改变的状态 |
| ---------------------------------- | ---------------------------------------------- | -------------------------------------- |
| `animate(content)` | 无 | 当前对象,以及该对象的步骤容器 |
| `curve(curve)` | 无 | 当前曲线,供后续 `to` 记录 |
| `to(value, time, end)` | 当前对象、当前曲线、当前触发基准 | 向当前计划组写入一条步骤,步骤编号加一 |
| `after(time)` / `when(time)` | 上一个定义的步骤 | 触发基准与等待时长 |
| `afterPlan(...)` / `whenPlan(...)` | 当前计划组中指定对象、指定编号的步骤 | 触发基准与等待时长 |
| `planEnd(...)` | 当前计划组 | 关闭并排队该组,返回组编号 |
| `query(...)` | 默认读取当前正在定义的组 | 无 |
| `wait(...)` | 默认读取当前正在执行的组;没有时读正在定义的组 | 无 |
| `destroy()` | 无 | 解绑激励源,清空计划与执行状态 |
其中最容易看错的是 `to`:它同时依赖选中的对象、当前曲线与当前触发基准。没有先用 `animate` 选中对象时,`to` 不写入任何步骤,计划看起来写了,实际不会动。
`after` 与 `when` 改的是触发基准,不是当前对象。之后即使换了对象,基准也会保持,直到下一次触发设置或 `planEnd`。
`query` 与 `wait` 的默认范围不同:`query` 默认读当前正在定义的组;`wait` 默认读当前正在执行的组,没有执行中的组时读当前正在定义的组。
## 组合与编排示例
下面每个示例前都先说明它表示的动画;示例里的 `x`、`y` 是已经声明好的动画对象,`animater` 由 `useAnimater()` 取得,`linear()` 来自 `@motajs/animate`。每个示例后配两个 live:一个看时间轴,一个看数值播放;两者都由真实执行器推进。
### 顺序执行
这个示例表示:`x` 先走完,`y` 才开始。
```ts
// x 走完,y 才开始
animater
.animate(x) // 当前对象:x;尚无步骤;选择 x
.curve(linear()) // 当前对象:x;尚无步骤;设置当前曲线
.to(1, 700) // 当前对象:x;新增索引 1;写入步骤
.after() // 当前对象:x;索引 1;把后续步骤挂到索引 1 结束之后
.animate(y) // 当前对象:y;尚无步骤;选择 y
.to(1, 450) // 当前对象:y;新增索引 1;写入步骤(挂到 x 索引 1 结束之后)
.planEnd(); // 当前对象:y;索引 1;结束本组,当前对象清空
```
`after()` 不等待额外时间,所以 `y` 在 `x` 结束的同一刻启动。
时间轴视图:色块是步骤段,竖线是播放头。
<ClientOnly>
<RenderDemo :loader="sequentialTimelineLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
播放视图:两个圆点分别表示 `x` 与 `y` 的当前值。
<ClientOnly>
<RenderDemo :loader="sequentialPlaybackLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 并行执行
这个示例表示:`x` 与 `y` 同时开始,各自走向自己的目标。
```ts
// x、y 同时开始,各自走向自己的目标
animater
.animate(x) // 当前对象:x;尚无步骤;选择 x
.curve(linear()) // 当前对象:x;尚无步骤;设置当前曲线
.to(1, 900) // 当前对象:x;新增索引 1;写入步骤(随组开始)
.animate(y) // 当前对象:y;尚无步骤;选择 y
.curve(linear()) // 当前对象:y;尚无步骤;设置当前曲线
.to(0.5, 900) // 当前对象:y;新增索引 1;写入步骤(随组开始,与 x 并行)
.planEnd(); // 当前对象:y;索引 1;结束本组,当前对象清空
```
两条步骤都没有挂触发点,所以都会随组开始;它们只共享开始时刻,不共享目标、时长或曲线。
时间轴视图:两条步骤段从同一刻开始。
<ClientOnly>
<RenderDemo :loader="parallelTimelineLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
播放视图:两个值同时变化。
<ClientOnly>
<RenderDemo :loader="parallelPlaybackLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 延迟与重叠
这个示例表示:`x` 先开始,`y` 在 `x` 开始 300ms 后启动,两者重叠 600ms。
```ts
// x 先走 1000ms,y 在 x 开始 300ms 后启动,两者重叠 600ms
animater
.animate(x) // 当前对象:x;尚无步骤;选择 x
.curve(linear()) // 当前对象:x;尚无步骤;设置当前曲线
.to(1, 1000) // 当前对象:x;新增索引 1;写入步骤
.when(300) // 当前对象:x;索引 1;把后续步骤挂到索引 1 开始之后,等待 300ms
.animate(y) // 当前对象:y;尚无步骤;选择 y
.to(1, 600) // 当前对象:y;新增索引 1;写入步骤(挂到 x 索引 1 开始之后)
.planEnd(); // 当前对象:y;索引 1;结束本组,当前对象清空
```
`when(300)` 以 `x` 的开始为基准,所以 `y` 在 `x` 走了 300ms 时启动,而不是等 `x` 结束。
时间轴视图:`y` 的步骤段从 `x` 中段开始。
<ClientOnly>
<RenderDemo :loader="delayedTimelineLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
播放视图:`x` 先动,`y` 稍后启动。
<ClientOnly>
<RenderDemo :loader="delayedPlaybackLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 两个计划组
这个示例表示:组 1 的 `x` 全部结束后,组 2 的 `y` 才开始;组间不需要额外写等待。
```ts
// 组 2 会等组 1 全部结束;不需要额外写等待
const first = animater // 当前对象:无;尚无步骤;开始定义组 1
.animate(x) // 当前对象:x;尚无步骤;选择 x
.curve(linear()) // 当前对象:x;尚无步骤;设置当前曲线
.to(1, 600) // 当前对象:x;新增索引 1;写入步骤
.planEnd(); // 当前对象:x;索引 1;结束组 1,当前对象清空
const second = animater // 当前对象:无;新组;开始定义组 2
.animate(y) // 当前对象:y;新组重新计数,尚无步骤;选择 y
.curve(linear()) // 当前对象:y;尚无步骤;设置当前曲线
.to(1, 600) // 当前对象:y;新增索引 1;写入步骤
.planEnd(); // 当前对象:y;索引 1;结束组 2,当前对象清空
// 等组 1 的 x 步骤,或等组 2 的 y 步骤,都可以
await animater.wait(x, 1, first); // 当前对象:无;组 first 索引 1;等待 x
await animater.wait(y, 1, second); // 当前对象:无;组 second 索引 1;等待 y
```
时间轴视图:两组首尾相接,中间没有重叠。
<ClientOnly>
<RenderDemo :loader="relayTimelineLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
播放视图:`x` 完成后,`y` 才从 0 开始。
<ClientOnly>
<RenderDemo :loader="relayPlaybackLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 查询与等待指定步骤
这个示例表示:先读出 `y` 这条步骤的目标与时长,再只等待 `y` 结束。
```ts
const group = animater // 当前对象:无;尚无步骤;开始定义一组
.animate(x) // 当前对象:x;尚无步骤;选择 x
.curve(linear()) // 当前对象:x;尚无步骤;设置当前曲线
.to(1, 300) // 当前对象:x;新增索引 1;写入步骤
.when(100) // 当前对象:x;索引 1;把后续步骤挂到索引 1 开始之后,等待 100ms
.animate(y) // 当前对象:y;尚无步骤;选择 y
.curve(linear()) // 当前对象:y;尚无步骤;设置当前曲线
.to(1, 200) // 当前对象:y;新增索引 1;写入步骤(挂到 x 索引 1 开始之后)
.planEnd(); // 当前对象:y;索引 1;结束本组,当前对象清空
const yStep = animater.query(y, 1, group); // 当前对象:无;组 group 索引 1;读取 y 的步骤
// yStep?.targetValue 为 1,yStep?.time 为 200
// 只等 y 这一条步骤,不等待整组
await animater.wait(y, 1, group); // 当前对象:无;组 group 索引 1;等待 y
```
这里的 `query` 与 `wait` 都显式传入了 `planEnd` 返回的组索引,所以查的是已封口的组,而不是之后还在定义的组。
时间轴视图:`x` 与 `y` 重叠,等待只针对 `y` 那一段。
<ClientOnly>
<RenderDemo :loader="queryTimelineLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
播放视图:先显示查到的 `y` 目标与时长,再播放数值。
<ClientOnly>
<RenderDemo :loader="queryPlaybackLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
### 中途改道
这个示例表示:`x` 的第一段走到 700ms 时被第二段接管,改为走回 0;`y` 仍按自己的节奏走完。
```ts
const group = animater // 当前对象:无;尚无步骤;开始定义一组
.animate(x) // 当前对象:x;尚无步骤;选择 x
.curve(linear()) // 当前对象:x;尚无步骤;设置当前曲线
.to(1, 1200, EndRelation.Self) // 当前对象:x;新增索引 1;写入步骤,结尾保留改道时的值
.animate(y) // 当前对象:y;尚无步骤;选择 y
.curve(linear()) // 当前对象:y;尚无步骤;设置当前曲线
.to(1, 1500) // 当前对象:y;新增索引 1;写入步骤
.whenPlan(x, 1, 700) // 当前对象:y;索引 1;把触发基准改为 x 索引 1 开始后 700ms
.animate(x) // 当前对象:x;已有索引 1;重新选择 x
.curve(linear()) // 当前对象:x;已有索引 1;设置当前曲线
.to(0, 500) // 当前对象:x;新增索引 2;写入步骤(挂到 x 索引 1 开始后 700ms)
.planEnd(); // 当前对象:x;索引 2;结束本组,当前对象清空
await animater.wait(x, 1, group); // 当前对象:无;组 group 索引 1;等待 x 第 1 段(改道时兑现)
await animater.wait(x, 2, group); // 当前对象:无;组 group 索引 2;等待 x 第 2 段
```
第一段使用 `EndRelation.Self`,接管时会停在改道时刻的值;如果使用默认的 `Target`,它会先跳到原来的目标值,再被新步骤拉回。被接管的那一段不会触发它挂的结束触发点。
时间轴视图:`x` 的第一段在 700ms 处截断,第二段从那里接上。
<ClientOnly>
<RenderDemo :loader="retargetTimelineLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
播放视图:`x` 在改道后从当前值走回 0,`y` 继续走完。
<ClientOnly>
<RenderDemo :loader="retargetPlaybackLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
## 与渐变执行器的分工
`Animater` 负责多个对象、多个步骤的编排;只是让单个数值连续靠近目标值时,用[渐变执行器](./animation-transition.md)。
## 边界与注意
- 同一个对象在同一时刻只能开始一条步骤:两条步骤同时启动会报错并跳过后一条;启动时刻更晚时,前一条会立刻结束再开始新的。
- `after` 与 `when` 锚定上一次定义的步骤,与当前 `animate` 选中的对象无关;中间换了对象,锚点也不会跟着换。
- 被接管的那一段不会触发它挂的结束触发点;需要停在接管时刻的值时用 `EndRelation.Self`,默认的 `Target` 会先跳到原目标值再被拉回。
<script setup>
import RenderDemo from '../../.vitepress/components/renderDemo.vue';
const timelineLoader = () =>
import('../../.vitepress/components/demos/ui/animater-timeline.tsx');
const sequentialTimelineLoader = () =>
import('../../.vitepress/components/demos/ui/animater-sequential-timeline.tsx');
const sequentialPlaybackLoader = () =>
import('../../.vitepress/components/demos/ui/animater-sequential-playback.tsx');
const parallelTimelineLoader = () =>
import('../../.vitepress/components/demos/ui/animater-parallel-timeline.tsx');
const parallelPlaybackLoader = () =>
import('../../.vitepress/components/demos/ui/animater-parallel-playback.tsx');
const delayedTimelineLoader = () =>
import('../../.vitepress/components/demos/ui/animater-delayed-timeline.tsx');
const delayedPlaybackLoader = () =>
import('../../.vitepress/components/demos/ui/animater-delayed-playback.tsx');
const relayTimelineLoader = () =>
import('../../.vitepress/components/demos/ui/animater-relay-timeline.tsx');
const relayPlaybackLoader = () =>
import('../../.vitepress/components/demos/ui/animater-relay-playback.tsx');
const queryTimelineLoader = () =>
import('../../.vitepress/components/demos/ui/animater-query-timeline.tsx');
const queryPlaybackLoader = () =>
import('../../.vitepress/components/demos/ui/animater-query-playback.tsx');
const retargetTimelineLoader = () =>
import('../../.vitepress/components/demos/ui/animater-retarget-timeline.tsx');
const retargetPlaybackLoader = () =>
import('../../.vitepress/components/demos/ui/animater-retarget-playback.tsx');
</script>
@@ -0,0 +1,253 @@
# 渐变执行器
渐变执行器 `Transition` 实现 `ITransition`,负责让一个数值平滑地靠近目标值。它只处理一个数值、一段时长和一条曲线;需要给多个值排先后、控制并行关系时,使用[动画执行器](./animation-runner.md)。
## 模型
一次渐变只有四样东西:
| 组成 | 是什么 |
| ---------- | --------------------------------------------------------- |
| 当前值 | 可写对象上的 `value`,渐变过程中由执行器更新 |
| 目标值 | 这次要靠近的数,由 `to` 的第一个参数给出 |
| 时长与曲线 | 用多久走完,以及过程中快慢怎么变化 |
| 激励源 | 按固定节奏推动执行器的来源,由 `useTransition` 或手动接入 |
`IAnimatable` 是动画对象的形状:一个带可写 `value` 的对象,Vue 的 `ref<number>` 也满足这个形状。当前值由执行器改写,调用方只读它。
曲线决定的是「已经走了多远」。它接收时间进度 `progress`(`0` 到 `1`),返回一个数;这个数表示此时刻动画的完成度:为 `0` 时动画处于起点,为 `1` 时刚好执行到目标值,中间按曲线返回的比例推进。
曲线返回值超出 `0` 到 `1` 时,当前值会越过目标值,或回到起始值之外。
调用 `to` 后,执行器记下目标值、时长与曲线。之后每次激励,它就让当前值向目标值靠近一点;到达结尾时,按结尾参考决定最终写什么值。没有激励源,`to` 不会开始。
```mermaid
flowchart LR
E[激励源] -->|excited| T[Transition]
T -->|更新当前值| V[IAnimatable.value]
C[to:目标值 / 时长 / 曲线] --> T
```
`ITransition` 本身是一个受激励对象(`IExcitable<number>`):它接收激励源按节奏传来的数字时间戳,再推进自己的渐变。通过 `bindExcitation` 接入激励源、通过 `unbindExcitation` 解除。组件里通常交给 `useTransition`;不在组件内,或需要接到自定义激励源时,才手动绑定。
下面的 live 用真实的 `Transition` 驱动数值。当前值与目标值同时显示,按钮会重新设定目标,执行器从当前值继续渐变。
<ClientOnly>
<RenderDemo :loader="transitionLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
## 执行器
自己 `new` 执行器还要手动找激励源并处理解绑,组件卸载时很容易漏掉清理;`useTransition` 把这些事收在一处。它必须在组件的 `setup` 或生命周期钩子里调用:它会把执行器绑定到根渲染器的激励源,并在组件卸载时解除绑定。
```tsx
// setup
import { defineComponent, ref } from 'vue';
import { useTransition } from '@motajs/render-vue';
const MyPanel = defineComponent(() => {
const opacity = ref(0);
// 只能在组件 setup 或生命周期钩子里调用
const transition = useTransition()!;
// 之后的 transition.transition(...).to(...) 都通过它执行
return () => <container loc={[0, 0, 100, 100]} alpha={opacity.value} />;
});
```
`useTransition(tran?, excitation?)` 返回 `ITransition | null`。两个参数都可选:`tran` 是已有的执行器,`excitation` 是显式指定的激励源。省略时,函数会新建一个 `Transition`,并绑定根渲染器的激励源。
不传 `tran` 时,执行器由 `useTransition` 创建,组件卸载时会解除绑定并销毁它;传入 `tran` 时,函数只负责绑定与解绑,执行器仍由调用方持有。根渲染器变化时,两种情况都会重新绑定到新的激励源。
不在组件内,或需要接到自定义激励源时,才自己创建执行器并手动绑定。`RafExcitation` 是一个每帧给出时间戳的激励源,`Transition` 是渐变执行器本身:
```ts
import { RafExcitation, Transition } from '@motajs/animate';
const excitation = new RafExcitation();
const transition = new Transition();
// 绑定后执行器才会收到每一帧的时间戳
transition.bindExcitation(excitation);
// 不再使用时解绑
transition.unbindExcitation();
```
手动创建时,解绑与销毁由调用方负责;`useTransition` 只是替组件内场景处理了这些收尾。
## 对象选择
`to` 只会改「当前选中的对象」,所以开始渐变的下一步是告诉执行器改谁;不先选对象,后面的目标值没有落点。
`transition(animatable)` 选择后续 `to` 作用的数值对象,返回执行器本身,可以继续链式调用。
```ts
const opacity = ref(0);
const transition = useTransition()!;
transition.transition(opacity).to(1, 300);
```
同一个执行器可以依次选择不同对象,各自调用 `to`;每个对象的渐变独立进行,`wait` 也按对象区分。`transition` 只改变「之后调用 `to` 时作用在谁身上」,不会停止之前已经在进行的渐变。
```ts
import { ref } from 'vue';
import { linear, sin } from '@motajs/animate';
import { useTransition } from '@motajs/render-vue';
const leftBar = ref(0);
const rightBar = ref(1);
const transition = useTransition()!;
function playBars() {
// 选中 leftBar,后面的 to 只作用于它
transition.transition(leftBar).curve(linear()).to(1, 600);
// 再选中 rightBar,两条渐变同时推进
transition.transition(rightBar).curve(sin()).to(0, 600);
}
```
`playBars` 调用后,`leftBar` 与 `rightBar` 各自有一段正在进行的渐变;执行器每次被激励都会把两条都推进一次。它们只共享激励源,不共享目标、时长或曲线。
## 曲线设置
同样一段时间,是匀速走完还是先慢后快,由曲线决定;想要淡入淡出、回弹或强调结尾时,需要在这里换掉默认的线性曲线。
`curve(curve)` 设置后续 `to` 使用的速率曲线,直到下一次设置;不设置时使用线性曲线。曲线决定过程中的快慢,`time` 决定总耗时。
```ts
import { sin } from '@motajs/animate';
transition.transition(opacity).curve(sin()).to(1, 300);
```
一次渐变会使用调用 `to` 时已经设好的曲线;之后再改 `curve`,不会影响已经开始的那一次。需要让不同目标使用不同节奏时,在每次 `to` 前重新设置。各条曲线的形状见[动画曲线](./animation-curves.md)。
## 开始渐变
前面的选择与曲线只是准备,真正让数值开始变化的是 `to`;没有它,执行器不会产生任何一段渐变。
`to(value, time, end?)` 让当前选中的对象从自己的当前值出发,在 `time` 毫秒内走向 `value`。它需要两个前提:已经用 `transition` 选择了对象,并且已经绑定激励源;缺少任意一项时,调用不会开始渐变。使用顺序是:先用 `transition(对象)` 选中要改的数值,再用 `curve(...)` 选好曲线,最后调用 `to(...)` 启动渐变。
同一个对象在渐变途中再次调用 `to`,会从当前值重新出发,把目标改为新的值。之前那次渐变的等待仍会在新目标完成时兑现。
```ts
const opacity = ref(0);
function fadeIn() {
transition.transition(opacity).to(1, 600);
}
function dim() {
// 如果 fadeIn 还没结束,会从当前值出发,把目标改成 0.4
transition.transition(opacity).to(0.4, 300);
}
```
## 结尾参考
曲线走到终点时未必等于目标值,最后该写哪一个需要明确;`EndRelation` 就是在回答这个问题,默认会直接写目标值。
`to` 的第三个参数是 `EndRelation`,决定渐变结束时把值写成什么:
| 结尾参考 | 结束时的值 |
| -------------------- | --------------------------------------------------- |
| `EndRelation.Target` | 直接写成传入的目标值,默认使用这一种 |
| `EndRelation.Curve` | 结束时使用曲线终点值参考,不强制把值写成目标值 |
| `EndRelation.Self` | 正常结束时与 `Curve` 相同;提前结束时停在打断时的值 |
使用 `Curve` 时,结束值由曲线终点决定,不强制等于目标值:曲线终点回到起点附近,值也会停在起点附近;曲线终点越过目标值,值也会停在越过后的位置。
```ts
import { ref } from 'vue';
import { EndRelation } from '@motajs/animate';
// 曲线在终点只走了一半,所以 Curve 模式会停在半程
const half = (p: number) => p * 0.5;
const value = ref(0);
transition.transition(value).curve(half).to(1, 500, EndRelation.Curve);
```
下面的 live 并排比较 `Target` 与 `Curve`。曲线可以在「半程曲线」与「回程曲线」之间切换;后者到终点会回到起点,所以 `Curve` 那条也会回到起点。
<ClientOnly>
<RenderDemo :loader="endRelationLoader" :width="480" :height="320" />
<template #fallback>
渲染示例需要浏览器环境。
</template>
</ClientOnly>
## 完成等待
要让两段动画接上,调用方需要知道上一段什么时候结束;`wait` 把这段时间变成一个可等待的信号,避免用定时器猜。
`wait(animatable)` 返回该对象当前渐变的 `Promise`;对象没有活动渐变时立即兑现。它只等待传入的对象,不等待其他对象的渐变。用法顺序是:先调用 `to` 启动一段渐变,再对同一个对象 `await wait(...)`。
```ts
async function fadeTo(value: number): Promise<void> {
transition.transition(opacity).to(value, 300);
await transition.wait(opacity);
}
```
`wait` 在渐变途中被调用时,等待的是该对象当前这次渐变;如果中途又调用了 `to`,同一个 `Promise` 会在新目标完成时兑现。把多个 `to` 与 `wait` 串起来,就能写出顺序步骤:
```ts
async function runStroke() {
// 第一段:正弦曲线,400ms 走到 1
transition.transition(marker).curve(sin()).to(1, 400);
await transition.wait(marker);
// 第二段:线性曲线,900ms 回到 0
transition.transition(marker).curve(linear()).to(0, 900);
await transition.wait(marker);
}
```
第一段结束后,`wait` 才让出执行权;第二段从第一段写回的当前值继续。需要计划级等待时使用 `Animater`。
## 释放与销毁
执行器会持有选中的对象和激励源绑定;组件或动画结束时如果一直不清理,它就会继续惦记这些对象。
`revoke()` 释放当前通过 `transition` 选中的对象,避免执行器一直持有它;它不会停止已经开始的渐变。释放后,新的 `to` 需要重新用 `transition` 选择对象。清理顺序是:先 `revoke()` 放掉选中的对象,再按需重新 `transition` 选择;要停止整个执行器时再用 `destroy()`。
`destroy()` 解除激励源绑定并清理执行器;之后这个执行器不能再推进。由 `useTransition` 内部创建的执行器会在组件卸载时自动销毁;传入已有执行器时,组件卸载只解除绑定。
```ts
const transition = useTransition()!;
const opacity = ref(0);
transition.transition(opacity).to(1, 600);
// 释放选中对象:渐变继续,但之后的 to 需要重新 transition 选择
transition.revoke();
transition.transition(opacity).to(0.2, 300);
// 解除激励源绑定:之后不会再推进
transition.destroy();
```
## 与动画执行器的分工
| 项目 | `Transition` | `Animater` |
| -------- | ---------------------------- | ----------------------------------- |
| 组织单位 | 单个数值的连续渐变 | 多个动画对象与多个计划组 |
| 时序关系 | 只有当前渐变的时长 | `after`、`when`、组前等待、组后等待 |
| 典型用途 | 淡入淡出、悬停反馈、颜色过渡 | 多对象编排、分段动画、并行与延迟 |
需要「一个数慢慢变成另一个数」时用 `Transition`;需要给多个值排先后顺序、设置延迟或并行关系时,用[动画执行器](./animation-runner.md)。
<script setup>
import RenderDemo from '../../.vitepress/components/renderDemo.vue';
const transitionLoader = () =>
import('../../.vitepress/components/demos/ui/animation-transition.tsx');
const endRelationLoader = () =>
import('../../.vitepress/components/demos/ui/animation-transition-end-relation.tsx');
</script>