In the following code I program a canvas and display a red block that grows in width as the game progresses. It all worked too! Until, I added a simple game loop to my originally (simpler) game loop. The original just updated, rendered, and restarted. The modern newer one Counts ticks and keeps it running at a consistent speed, no matter how fast the computer/browser. Can anyone explain why this is? Here is the plain html to set up everything:
<html>
<head>
<meta charset="utf-8">
<title>Christmas Town</title>
<style>
canvas {
display: block;
position: fixed;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
</head>
<body>
<script src="game.js"></script>
</body>
</html>
And here is the JavaScript which is supposed to create the canvas and Game Loop:
var canvas, context, keyState;
var width = 0;
function tick() {
"use strict";
console.log(5 + 6);
if (width < canvas.getWidth()) {
width += 1;
}
}
function render() {
"use strict";
context.fillStyle = "#FF0000";
context.fillRect(canvas.width, canvas.height, 0, 0);
context.save();
context.fillRect(width, 15, 0, 0);
context.restore();
}
function getTimeMillis() {
"use strict";
return window.performance && window.performance.now ? window.performance.now : new Date.getTime();
}
var FPS = 60, startTime, dt = 0, lastTime = getTimeMillis(), targetTime = 1 / FPS;
function frame() {
"use strict";
startTime = getTimeMillis();
dt = dt + Math.min(1, ((startTime - lastTime) / 1000));
while (dt < targetTime) {
dt -= targetTime;
tick();
}
render();
lastTime = startTime;
window.requestAnimationFrame(frame, canvas);
}
function main() {
"use strict";
canvas = document.createElement("canvas");
canvas.width = 500;
canvas.height = 500;
context = canvas.getContext("2d");
document.body.appendChild(canvas);
window.requestAnimationFrame(frame, canvas);
}
main();
The weird part is it's not even logging to the console, and there are no errors! But, I cant seem to figure out why tick is not being called without there being any errors. Please help!
window.performance.now() : new Date().getTime()andstartTime = getTimeMillis();