so://phie

game-engine

A lightweight JavaScript game engine
git clone git://soophie.de/game-engine

blob: 7b3733b2a661b21d082737ba86f7009b6107e7a1 (991 bytes)[doc][blame][raw]

1const cache = new Map();

2

3export default class Sprite {

4 constructor(path) {

5 this.path = path;

6 this.image = new Image();

7 }

8 load() {

9 return new Promise(async (resolve, reject) => {

10 this.image.onload = () => {

11 if(!cache.has(this.path)) {

12 cache.set(this.path, this.image.src);

13 }

14 resolve();

15 };

16 this.image.onerror = () => {

17 reject(new Error(`Unable to load sprite '${this.path}'!`));

18 }

19 if(cache.has(this.path)) {

20 this.image.src = cache.get(this.path);

21 }

22 else {

23 if(this.path.startsWith('data:')) {

24 this.image.src = this.path;

25 }

26 else {

27 try {

28 const response = await fetch(this.path);

29 if(response.status !== 200) {

30 reject(new Error(`Invalid response code ${response.status} for sprite '${this.path}'!`));

31 }

32 const blob = await response.blob();

33 const url = URL.createObjectURL(blob);

34 this.image.src = url;

35 }

36 catch(error) {

37 reject(error);

38 }

39 }

40 }

41 });

42 }

43}