Skip to content

Commit

Permalink
Basic loop
Browse files Browse the repository at this point in the history
  • Loading branch information
ftripier committed Aug 22, 2018
1 parent 770fcfc commit a4216e8
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 3 deletions.
10 changes: 10 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<html>
<head>
<title>Classical Mechanics</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<canvas id="canvas"></canvas>
<script src="dist/index.js"></script>
</body>
</html>
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,8 @@
},
"dependencies": {
"tslint-config-airbnb": "^5.10.0"
},
"scripts": {
"dev": "tsc -w"
}
}
73 changes: 70 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,72 @@
const world = "🗺️";
interface State {
startTime: number;
time: number;
dt: number;
width: number;
height: number;
}

class Engine {
queue: Function[];
ctx: CanvasRenderingContext2D;
state: State;
constructor(canvas: HTMLCanvasElement) {
this.queue = [];
const ctx = <CanvasRenderingContext2D>canvas.getContext("2d");
this.ctx = ctx;
this.state = {
startTime: 0,
time: 0,
dt: 0,
width: 0,
height: 0
};

const resizeCanvas = () => {
const canvas = <HTMLCanvasElement>document.getElementById("canvas");
const width = window.innerWidth;
const height = window.innerHeight;
if (canvas) {
canvas.height = height;
canvas.width = width;
}
this.state.width = width;
this.state.height = height;
};
window.addEventListener("resize", () => {
this.nextFrame(resizeCanvas);
});
resizeCanvas();
}

export function hello(word: string = world): string {
return `Hello ${world}! `;
nextFrame(cb: (state: State, ctx: CanvasRenderingContext2D) => void) {
this.queue.push(cb);
}

run(time?: number) {
if (!time) {
time = performance.now();
this.state.startTime = time;
}
this.state.dt = time - this.state.time;
this.state.time = time;
const enqeued = this.queue.length;
for (let i = 0; i < enqeued; i += 1) {
const cb = this.queue.shift();
if (cb) {
cb(this.state, this.ctx);
}
}
if (this.queue.length > 0) {
window.requestAnimationFrame(this.run.bind(this));
}
}
}

const canvas = <HTMLCanvasElement>document.getElementById("canvas");
const engine = new Engine(canvas);
const loop = (state: State, ctx: CanvasRenderingContext2D) => {
engine.nextFrame(loop);
};
engine.nextFrame(loop);
engine.run();

0 comments on commit a4216e8

Please sign in to comment.