so://phie

game-engine

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

blob: a1cbc329de724d5c8b0aae5a9af06ea8d0041dc6 (1207 bytes)[doc][blame][raw]

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

2

3export class Game {

4 constructor(width, height, { fps } = {}) {

5 this.width = width || 900;

6 this.height = height || 600;

7 this.fps = 1000 / (fps || 60);

8 this.then = Date.now();

9 this.canvas = document.createElement('canvas');

10 scaleCanvas(this.canvas, this.width, this.height);

11 this.g = this.canvas.getContext('2d');

12 this.events = [];

13 }

14 start() {

15 requestAnimationFrame(this.loop.bind(this));

16 this.update();

17 this.render(this.g);

18 }

19 loop() {

20 requestAnimationFrame(this.loop.bind(this));

21 this.now = Date.now();

22 this.elapsed = this.now - this.then;

23 if(this.elapsed > this.fps) {

24 this.then = this.now - (this.elapsed % this.fps);

25 for(const event of this.events) {

26 if(this['on' + event.type]) {

27 this['on' + event.type](event);

28 }

29 }

30 this.update();

31 this.render(this.g);

32 this.events.length = 0;

33 }

34 }

35 update() {

36 // nothing

37 }

38 render() {

39 this.g.clearRect(0, 0, this.width, this.height);

40 }

41 resize(width, height) {

42 this.width = width;

43 this.height = height;

44 scaleCanvas(this.canvas, this.width, this.height);

45 }

46 bindEvent(element, type) {

47 element['on' + type] = event => this.events.push(event);

48 }

49}