so://phie

game-engine

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

blob: 44ff4e963d2831697b426448cef00d8a09202424 (1119 bytes)[doc][blame][raw]

1import Sprite from './sprite.js';

2import { scaleCanvas } from '../util/canvas.js';

3

4export default class Spritesheet extends Sprite {

5 constructor(path, size) {

6 super(path);

7 this.size = size;

8 this.sprites = [];

9 }

10 async load() {

11 await super.load();

12 const {width, height} = this.image;

13 if(width % this.size !== 0 || height % this.size !== 0) {

14 throw new Error(`Invalid size ${this.size} for spritesheet '${this.path}'!`);

15 }

16 this.sprites = new Array(parseInt(width / this.size) * parseInt(height / this.size));

17 const canvas = document.createElement('canvas');

18 scaleCanvas(canvas, this.size, this.size);

19 const g = canvas.getContext('2d');

20 g.imageSmoothingEnabled = false;

21 for(let i = 0; i < this.sprites.length; i++) {

22 const y = parseInt(i / (width / this.size));

23 const x = parseInt(i % (width / this.size));

24 g.clearRect(0, 0, this.size, this.size);

25 g.drawImage(this.image, -x * this.size, -y * this.size, width, height);

26 const sprite = new Sprite(canvas.toDataURL('image/png'));

27 await sprite.load();

28 this.sprites[i] = sprite;

29 }

30 }

31 all() {

32 return this.sprites;

33 }

34}