A lightweight JavaScript game engine
git clone git://soophie.de/game-engine
blob: 35768e3632d570977b9305f85feff79c75d4e55a (1142 bytes)[doc][blame][raw]
1
import Sprite from './sprite.js';2
import { scaleCanvas } from 'https://git.typable.dev/std/js/canvas.js';4
export 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
}