Skip to content

Instantly share code, notes, and snippets.

@AyaMorisawa
Created December 4, 2015 18:24
Show Gist options
  • Save AyaMorisawa/0e95d2cf5fc8e0ae145f to your computer and use it in GitHub Desktop.
Save AyaMorisawa/0e95d2cf5fc8e0ae145f to your computer and use it in GitHub Desktop.
var canvas;
var ctx;
var x;
var y;
var isRightPressed;
var isLeftPressed;
var isUpPressed;
var isDownPressed;
window.addEventListener('load', function() {
canvas = document.getElementById('main');
canvas.width = 800;
canvas.height = 600;
ctx = canvas.getContext('2d');
x = 0;
y = 0;
window.addEventListener('keydown', function(e) {
if (e.which === 39) {
isRightPressed = true;
}
if (e.which === 37) {
isLeftPressed = true;
}
if (e.which === 40) {
isDownPressed = true;
}
if (e.which === 38) {
isUpPressed = true;
}
});
window.addEventListener('keyup', function(e) {
if (e.which === 39) {
isRightPressed = false;
}
if (e.which === 37) {
isLeftPressed = false;
}
if (e.which === 40) {
isDownPressed = false;
}
if (e.which === 38) {
isUpPressed = false;
}
});
window.addEventListener('blur', function() {
isRightPressed = false;
isLeftPressed = false;
isDownPressed = false;
isUpPressed = false;
});
requestAnimationFrame(update);
});
function update() {
render();
if (isRightPressed) {
x = x + 5;
}
if (isLeftPressed) {
x = x - 5;
}
if (isDownPressed) {
y = y + 5;
}
if (isUpPressed) {
y = y - 5;
}
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (750 < x) {
x = 750;
}
if (550 < y) {
y = 550;
}
requestAnimationFrame(update);
}
function render() {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, 800, 600);
ctx.fillStyle = 'red';
ctx.fillRect(x, y, 50, 50);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment