//I did this very differently than you showed us, I hope that's fine
/*************
variables to make program work
*************/
//access the canvas
var canvas = document.getElementById('myCanvas');
//access drawing environment
var context = canvas.getContext("2d");
var x = 240;
var y = 240;
var XSpeed = 0;
var YSpeed = 0;
var speedMult = 1;
/***********
function for drawing stuff
************/
function draw() {
//background
context.fillStyle = "lightBlue";
context.fillRect(0, 0, 500, 500);
//Cubeman
context.fillStyle = "white";
context.fillRect(x, y, 20, 20);
//Everything involving keys
document.onkeydown = function(e) {
var e = window.event || e;
var key = e.keyCode;
e.preventDefault();
//key inputs
if (key === 68 && x < 477) {
XSpeed = 3;
YSpeed = 0;
}
if (key === 65 && x > 3) {
XSpeed = -3;
YSpeed = 0;
}
if (key === 87 && y > 3) {
YSpeed = -3;
XSpeed = 0;
}
if (key === 83 && y < 477) {
YSpeed = 3;
XSpeed = 0;
}
if (key === 32 && speedMult < 9) {
speedMult = speedMult + 1;
}
}
//MOVEMENT
x = x + (XSpeed * speedMult);
y = y + (YSpeed * speedMult);
//Checking for Collision
if (x > 477 || x < 3) {
XSpeed = 0;
} else if (y > 477 || y < 3) {
YSpeed = 0;
}
}
/************
Call the function
************/
var framerate = 1000 / 30;
var thread = setInterval(draw, framerate);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.