-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathspritesheet.ts
More file actions
68 lines (60 loc) · 1.72 KB
/
spritesheet.ts
File metadata and controls
68 lines (60 loc) · 1.72 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { isBrowser } from "./keyframes";
import { KeyframeObject, KeyframeRule, IterationCount } from "./types/keyframes";
type SpriteSheetOptions = {
name: string,
rows?: number,
cols?: number,
height?: number,
width?: number,
offsetX?: number,
offsetY?: number,
count?: number,
spriteWidth?: number,
spriteHeight?: number,
loop?: boolean,
};
export const spriteSheet = ({
rows = 1,
cols = 1,
width = 0,
height = 0,
...rest
}: SpriteSheetOptions): KeyframeObject => {
const defaults = {
offsetX: 0,
offsetY: 0,
count: rows * cols,
spriteWidth: width / cols,
spriteHeight: height / rows,
loop: true,
};
const opts = { ...defaults, rows, cols, width, height, ...rest };
const spriteStep = 100 / opts.count;
const spriteFrames: KeyframeRule = {};
let x = opts.offsetX;
let y = opts.offsetY;
for (let i = 0; i < opts.count; i += 1) {
spriteFrames[`${Math.round(spriteStep * i)}%`] = {
backgroundPosition: `-${x}px -${y}px`,
};
if (x >= opts.width - opts.spriteWidth) {
y += opts.spriteHeight;
} else {
x += opts.spriteWidth;
}
}
return Object.assign({}, { name: opts.name }, spriteFrames);
};
export const playSpriteSheet = (name: string, time: string | 0, loops: IterationCount = 'infinite'): string => {
if (loops && loops < 0) {
loops = 'infinite';
}
return `${name} ${time} steps(1) ${loops}`;
};
if (isBrowser) {
const _window = (window as any);
if (_window.Keyframes) {
_window.Keyframes.spriteSheet = spriteSheet;
_window.Keyframes.playSpriteSheet = playSpriteSheet;
}
}