so://phie

game-engine

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

blob: 43e7a92d18ae490b3d16ceabf4a05b4fe35cdeeb (888 bytes)[doc][blame][raw]

1import { scaleCanvas } from './canvas.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 }

13 start() {

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

15 this.update();

16 this.g.save();

17 this.render(),

18 this.g.restore();

19 }

20 loop() {

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

22 this.now = Date.now();

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

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

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

26 this.update();

27 this.g.save();

28 this.render(),

29 this.g.restore();

30 }

31 }

32 update() {

33 // empty

34 }

35 render() {

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

37 }

38}