-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuseAnimatedSprite.ts
More file actions
50 lines (41 loc) · 1.22 KB
/
useAnimatedSprite.ts
File metadata and controls
50 lines (41 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { useEffect } from "react";
import { SpriteProps } from "./useSprite";
type AnimatedSpriteProps = SpriteProps & {
animationLength: number;
animationSpeed: number;
};
export const useAnimatedSprite = (props: AnimatedSpriteProps) => {
useEffect(() => {
const ctx = props.canvasRef.current?.getContext("2d");
let intervalId: number;
if (!props.canvasRef.current || !ctx) {
return;
}
props.left && (props.canvasRef.current.style.left = `${props.left}px`);
props.top && (props.canvasRef.current.style.top = `${props.top}px`);
const sprite = new Image();
sprite.src = props.tileSet;
sprite.onload = () => {
let currentFrame = 0;
intervalId = window.setInterval(() => {
ctx.clearRect(0, 0, props.width, props.height);
ctx.drawImage(
sprite,
props.tileX + props.width * currentFrame,
props.tileY,
props.width,
props.height,
0,
0,
props.width,
props.height
);
currentFrame =
currentFrame === props.animationLength ? 0 : currentFrame + 1;
}, props.animationSpeed);
};
return () => {
clearInterval(intervalId);
};
}, [props]);
};