Skip to content

Instantly share code, notes, and snippets.

@tokland
Forked from andreuestanyalonso/game.js
Last active June 13, 2020 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tokland/39b71d9697ea7db1132ef2e9aac088b6 to your computer and use it in GitHub Desktop.
Save tokland/39b71d9697ea7db1132ef2e9aac088b6 to your computer and use it in GitHub Desktop.
Simple Canvas game loop with key events
const canvas = document.getElementById("tutorial");
const context = canvas.getContext("2d");
function drawBackground() {
context.beginPath();
context.fillStyle = "rgb(200, 200, 200)";
context.rect(0, 0, 640, 480);
context.fill();
context.closePath();
}
function drawRectangle() {
context.beginPath();
context.fillStyle = "rgb(200, 0, 0)";
context.rect(100, 100, 200, 40);
context.fill();
context.closePath();
}
function drawTriangle() {
context.beginPath();
context.fillStyle = "rgb(0, 200, 0)";
context.moveTo(400, 100);
context.lineTo(300, 250); // 1
context.lineTo(500, 250); // 2
context.fill();
context.closePath();
}
function drawCircle(radius, x, y) {
context.beginPath();
context.fillStyle = "rgb(0, 0, 200)";
context.arc(x, y, radius, 0, 2 * Math.PI);
context.fill();
context.closePath();
}
var x = 50;
var y = 50;
var radius = 100;
function draw(keys) {
drawBackground();
drawRectangle();
drawTriangle();
drawCircle(radius, x, y);
if (keys.ArrowRight) {
x = x + 1;
}
if (keys.ArrowLeft) {
x = x - 1;
}
if (keys.ArrowDown) {
y = y + 1;
}
if (keys.ArrowUp) {
y = y - 1;
}
}
function loop(drawFn) {
let keys = {};
const drawRecursive = () => {
drawFn(keys);
window.requestAnimationFrame(drawRecursive);
};
window.addEventListener("keydown", (ev) => {
keys[ev.code] = true;
});
window.addEventListener("keyup", (ev) => {
keys[ev.code] = false;
});
window.requestAnimationFrame(drawRecursive);
}
loop(draw);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment