Skip to content

Commit

Permalink
feat: add restore methods of svg animation
Browse files Browse the repository at this point in the history
  • Loading branch information
kmkzt committed May 13, 2020
1 parent 3ad56de commit 204be98
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
19 changes: 9 additions & 10 deletions src/animation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ export class SvgAnimation extends Renderer {
public ms: number
private _stop: (() => void) | null
private _anim: FrameAnimation | null
private _restore: Path[]
private _restorePath: Path[]
constructor(el: HTMLElement, { background, ms }: AnimationOption) {
super(el, { background })
this.ms = ms ?? 60
this._stop = null
this._anim = null
this._restore = []
this._restorePath = []
}

public setAnimation(fn: FrameAnimation): void {
Expand All @@ -27,33 +27,32 @@ export class SvgAnimation extends Renderer {
}
}

public restore() {
this.replacePaths(this._restorePath)
this.update()
}

public frame() {
if (!this._anim) return
const updPaths = this._anim(this._restore.map(p => p.clone()))
const updPaths = this._anim(this._restorePath.map(p => p.clone()))
this.replacePaths(updPaths)
this.update()
}

public play(): void {
this.stop()
const ms = this.ms
this._restore = this.clonePaths()
this._restorePath = this.clonePaths()
const frame = () => {
if (ms !== this.ms) {
this.play()
return
}
this.frame()
}

const sceneChildrenRestore = () => {
this.replacePaths(this._restore)
this.update()
}
const stopId = setInterval(frame, ms)
this._stop = () => {
clearInterval(stopId)
sceneChildrenRestore()
this._stop = null
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/example/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,10 @@ const Example = () => {
if (!animationRef.current) return
animationRef.current.stop()
}, [])
const handleClickRestore = useCallback(() => {
if (!animationRef.current) return
animationRef.current.restore()
}, [])
// TODO: fix
// useEffect(() => {
// if (!divRef.current) return
Expand Down Expand Up @@ -394,6 +398,7 @@ const Example = () => {
<button onClick={handleClickShake}>SHAKING ANIMATION</button>
<button onClick={handleClickStrokeAnimation}>STROKE ANIMATION</button>
<button onClick={handleClickStop}>STOP</button>
<button onClick={handleClickRestore}>RESTORE</button>
<div>
ANIMATION MS
<input
Expand Down

0 comments on commit 204be98

Please sign in to comment.