mirror of
https://github.com/motion-canvas/motion-canvas.git
synced 2026-01-11 14:57:56 -05:00
feat: add useDuration helper (#226)
Added a `useDuration` helper function to easily create a `TimeEvent` and use it to control an animation. Added a sub-section for the new `useDuration` function in the `Time Events` chapter. Closes: #171
This commit is contained in:
@@ -17,3 +17,4 @@ export * from './useScene';
|
||||
export * from './useThread';
|
||||
export * from './useTime';
|
||||
export * from './useContext';
|
||||
export * from './useDuration';
|
||||
|
||||
31
packages/core/src/utils/useDuration.ts
Normal file
31
packages/core/src/utils/useDuration.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import {useScene} from './useScene';
|
||||
|
||||
/**
|
||||
* Register a time event and get its duration in seconds.
|
||||
*
|
||||
* @remarks
|
||||
* This can be used to better specify when an animation should start
|
||||
* as well as how long this animation should take
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* export default makeScene2D(function* (view) {
|
||||
* const circle = createRef<Circle>();
|
||||
*
|
||||
* view.add(
|
||||
* <Circle ref={circle} width={320} height={320} fill={'lightseagreen'} />,
|
||||
* );
|
||||
*
|
||||
* yield* circle().scale(2, useDuration('circleGrow'));
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param name - The name of the event.
|
||||
*
|
||||
* @returns The duration of the event in seconds.
|
||||
*/
|
||||
export function useDuration(name: string): number {
|
||||
const scene = useScene();
|
||||
scene.timeEvents.register(name);
|
||||
return scene.timeEvents.get(name).offset;
|
||||
}
|
||||
@@ -48,3 +48,14 @@ it. This is useful when you want to extend or shorten a pause in your voiceover
|
||||
because correcting the first time event after the pause will also fix all events
|
||||
after it. You can hold `SHIFT` when editing an event to prevent this from
|
||||
happening.
|
||||
|
||||
## Controlling animation duration
|
||||
|
||||
Aside from specifying _when_ something should happen, Time Events can also be used to
|
||||
control _how long_ something should last. You can use the
|
||||
[`useDuration`](/api/core/utils#useDuration) function to retrieve the duration of an event
|
||||
and use it in your animation:
|
||||
|
||||
```ts
|
||||
yield* circle().scale(2, useDuration('event'));
|
||||
```
|
||||
Reference in New Issue
Block a user