Skip to content

Instantly share code, notes, and snippets.

@emrivero
Created November 29, 2019 09:07
Show Gist options
  • Save emrivero/99853a6fda8fcb9a57a47c001b02d464 to your computer and use it in GitHub Desktop.
Save emrivero/99853a6fda8fcb9a57a47c001b02d464 to your computer and use it in GitHub Desktop.
Simple square movement
const canvas = document.querySelector('#canvas');
let posX = 0;
let posY = 0;
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(posX, posY, 20, 20);
const moveLeft = (ctx) => {
ctx.clearRect(posX, posY, 20, 20);
posX -= 10;
ctx.fillRect(posX, posY, 20, 20);
};
const moveRight = (ctx) => {
ctx.clearRect(posX, posY, 20, 20);
posX += 10;
ctx.fillRect(posX, posY, 20, 20);
};
const moveUp = (ctx) => {
ctx.clearRect(posX, posY, 20, 20);
posY -= 10;
ctx.fillRect(posX, posY, 20, 20);
};
const moveDown = (ctx) => {
ctx.clearRect(posX, posY, 20, 20);
posY += 10;
ctx.fillRect(posX, posY, 20, 20);
};
let keyPresses = {
a: false,
s: false,
d: false,
w: false,
};
document.addEventListener('keypress', (e) => {
const {
key
} = e;
console.log(e)
if (key === 'a') {
moveLeft(ctx);
keyPresses.a = true;
if (keyPresses.s) {
moveDown(ctx);
}
if (keyPresses.w) {
moveUp(ctx);
}
}
if (key === 'd') {
moveRight(ctx);
keyPresses.d = true;
if (keyPresses.s) {
moveDown(ctx);
}
if (keyPresses.w) {
moveUp(ctx);
}
}
if (key === 'w') {
moveUp(ctx);
keyPresses.w = true;
if (keyPresses.a) {
moveLeft(ctx);
}
if (keyPresses.d) {
moveRight(ctx);
}
}
if (key === 's') {
moveDown(ctx);
keyPresses.s = true;
if (keyPresses.a) {
moveLeft(ctx);
}
if (keyPresses.d) {
moveRight(ctx);
}
}
});
document.addEventListener('keyup', (e) => {
keyPresses[e.key] = false;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment