movement and key controls
by Kyle Bezio
HTML
<canvas width="500" height="500" id="myCanvas"></canvas>
CSS
#myCanvas {
border:1px solid #000;
}
JavaScript
//canvas values
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
//key codes
var left = 65;
var right = 68;
var up = 87;
var down = 83;
var boost = 32;
//variable to keep track of key pressed
var key = 0;
//location of rectangle
var x = 225;
var y = 225;
//speed of movement
var speed = 5;
/**
drawing
**/
function draw() {
//background
context.fillStyle = "white";
context.fillRect(0, 0, 500, 500);
//text
context.fillStyle = "black";
context.font = "20px Calibri";
context.fillText("Key: " + key, 0, 40);
context.fillText("W A S D to move", 100, 40);
//rectangle
context.fillStyle = "blue";
context.fillRect(x, y, 50, 50);
//call move function every time
speed = 5;
move();
}
/**
move the rectangle
**/
function move() {
//check for key value
if (key === right) {
//change x
x = x + speed;
}
//check for key value
if (key === left) {
//change x
x = x - speed;
}
//check for key value
if (key === up) {
//change y
y = y - speed;
}
//check for key value
if (key === down) {
//change y
y = y + speed;
}
}
//call the interval for animation and drawing
var thread = setInterval(draw, 1000 /60);
/**
key controls to capture key events
**/
document.onkeydown = function (e) {
//capture the event
e = window.event || e;
//get the key code
key = e.keyCode;
//prevent default event behavior
e.preventDefault();
};