Skip to content

Commit 24c5c9d

Browse files
committed
Init animation in setTime to start animation without calling play
1 parent 74dc11f commit 24c5c9d

File tree

2 files changed

+33
-22
lines changed

2 files changed

+33
-22
lines changed

src/react/hooks/useAnimation.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,20 @@ export const useAnimation = <Args = void>(
181181
return externalHandle;
182182
},
183183
setTime: (time) => {
184-
_setTime(getAnimation(), time);
184+
let animation = getAnimation();
185+
if (!animation) {
186+
if (!target || typeof keyframeRef.current === "function") {
187+
return externalHandle;
188+
}
189+
// Init animation in setTime to start animation without calling play
190+
const keyframes = normalizeKeyframe(
191+
target,
192+
keyframeRef.current,
193+
undefined
194+
);
195+
animation = initAnimation(target, keyframes);
196+
}
197+
_setTime(animation, time);
185198
return externalHandle;
186199
},
187200
setPlaybackRate: (rate) => {

stories/hooks/useAnimation.stories.tsx

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -460,13 +460,18 @@ export const Mouse: StoryObj = {
460460

461461
export const Scroll: StoryObj = {
462462
render: () => {
463+
const height = 2000;
464+
const duration = 500;
463465
const animate = useAnimation<{ top: number; left: number }>(
464-
(prev, pos) => [
465-
{ transform: prev.transform },
466-
{ transform: `translate(${pos.left}px,${pos.top}px)` },
466+
[
467+
{
468+
transform: `translate(0px,${height}px) rotate(${
469+
(height / 100) * 360
470+
}deg)`,
471+
},
467472
],
468473
{
469-
duration: 500,
474+
duration,
470475
easing: "ease-in-out",
471476
}
472477
);
@@ -481,36 +486,29 @@ export const Scroll: StoryObj = {
481486
width: "100vw",
482487
height: "100vh",
483488
}}
484-
onScroll={useMemo(
485-
() =>
486-
debounce(() => {
487-
if (!scrollRef.current) return;
488-
animate.play({
489-
restart: true,
490-
args: {
491-
top: scrollRef.current.scrollTop,
492-
left: scrollRef.current.scrollLeft,
493-
},
494-
});
495-
}, 100),
496-
[]
497-
)}
489+
onScroll={useCallback((e: React.UIEvent) => {
490+
if (!scrollRef.current) return;
491+
animate.setTime(
492+
e.currentTarget.scrollTop / (height / (duration * 4))
493+
);
494+
}, [])}
498495
>
499496
<div
500497
style={{
501498
position: "relative",
502-
width: 100000,
503-
height: 100000,
499+
height,
504500
}}
505501
>
506-
Please scroll!
502+
Please scroll down!
507503
<div
508504
ref={animate}
509505
style={{
510506
position: "absolute",
511507
background: "pink",
512508
height: "6rem",
513509
width: "6rem",
510+
top: 100,
511+
left: 100,
514512
}}
515513
/>
516514
</div>

0 commit comments

Comments
 (0)