A lightweight JavaScript game engine
git clone git://soophie.de/game-engine
blob: 826476a2846d6fdf87c88d467fc64fc6acbfd1b5 (1201 bytes)[doc][blame][raw]
1
import Sprite from './sprite.js';2
import { scaleCanvas } from '../util/canvas.js';4
export default class Spritesheet extends Sprite {5
constructor(path, width, height) {6
super(path);7
this.width = width;8
this.height = height || width;9
this.sprites = [];10
}11
async load() {12
await super.load();13
const {width, height} = this.image;14
if(width % this.width !== 0 || height % this.height !== 0) {15
throw new Error(`Invalid dimension ${this.width}x${this.height} for spritesheet '${this.path}'!`);16
}17
this.sprites = new Array(parseInt(width / this.width) * parseInt(height / this.height));18
const canvas = document.createElement('canvas');19
scaleCanvas(canvas, this.width, this.height);20
const g = canvas.getContext('2d');21
g.imageSmoothingEnabled = false;22
for(let i = 0; i < this.sprites.length; i++) {23
const y = parseInt(i / (width / this.width));24
const x = parseInt(i % (width / this.width));25
g.clearRect(0, 0, this.width, this.height);26
g.drawImage(this.image, -x * this.width, -y * this.height, width, height);27
const sprite = new Sprite(canvas.toDataURL('image/png'));28
await sprite.load();29
this.sprites[i] = sprite;30
}31
}32
all() {33
return this.sprites;34
}35
}