so://phie

game-engine

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

blob: 00188553191e49cd1cb2936fedf4e0afc6e50dee (1137 bytes)[doc][blame][raw]

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

2

3const cache = new Map();

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

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

6

7export default class Bitmap {

8 static from(sprite, width, height) {

9 const key = `${sprite.path}:${width}x${height}`;

10 if(!cache.has(key)) {

11 cache.set(key, new Bitmap(sprite.image, width, height));

12 }

13 return cache.get(key);

14 }

15 constructor(image, width, height) {

16 this.image = image;

17 this.width = width;

18 this.height = height;

19 scaleCanvas(canvas, width, height);

20 g.imageSmoothingEnabled = false;

21 g.drawImage(this.image, 0, 0, width, height);

22 const {data} = g.getImageData(0, 0, width, height);

23 this.map = [];

24 let row = [];

25 for(let i = 0; i < data.length; i += 4) {

26 const r = data[i];

27 const g = data[i + 1];

28 const b = data[i + 2];

29 const a = data[i + 3];

30 if((i / 4) % width === 0 && Math.floor(i / 4 / width) > 0) {

31 this.map.push(row);

32 row = [];

33 }

34 row.push([r, g, b, a]);

35 }

36 this.map.push(row);

37 }

38 get(x, y) {

39 if(x < 0 || y < 0 || x >= this.width || y >= this.height) {

40 return [];

41 }

42 return this.map[y][x];

43 }