-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuseSprite.ts
More file actions
44 lines (38 loc) · 1001 Bytes
/
useSprite.ts
File metadata and controls
44 lines (38 loc) · 1001 Bytes
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
import { useEffect, RefObject } from "react";
import { TILE_SETS } from "../constants";
export type SpriteProps = {
canvasRef: RefObject<HTMLCanvasElement>;
tileSet: TILE_SETS;
width: number;
height: number;
tileX: number;
tileY: number;
left?: number;
top?: number;
};
export const useSprite = (props: SpriteProps) => {
useEffect(() => {
const ctx = props.canvasRef.current?.getContext("2d");
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 = () => {
ctx.clearRect(0, 0, props.width, props.height);
ctx.drawImage(
sprite,
props.tileX,
props.tileY,
props.width,
props.height,
0,
0,
props.width,
props.height
);
};
}, [props]);
};