User Input
by DavisC_WL
HTML
<canvas width="500" height="500" id="myCanvas"></canvas>
CSS
#myCanvas {
border:1px solid #000;
}
JavaScript
/*************
variables to make program work
*************/
//access the canvas
var canvas = document.getElementById('myCanvas');
//access drawing environment
var ctx = canvas.getContext("2d");
//create a new image
//window.addEventListener("keydown", function(event) {}
//variables for rectangles
var speed = 0;
var key = -1;
var box = {
//variables that define the box
color:"red",
x:240,
y:240,
width:20,
height:20,
//function that tells the box to move
move:function(){
this.x = this.x+speed;
}
}
//capture the event key code
key = event.keyCode;
//event.preventDefault();
//}, true);
/***********
function for drawing stuff
************/
function draw() {
//color for the background
ctx.fillStyle = "white";
//shape to fill in the background
ctx.fillRect(0, 0, 500, 500);
//draw the box
ctx.fillStyle = box.color;
ctx.fillRect(box.x, box.y, box.width, box.height);
//write0 text to display the key
ctx.fillStyle = "black";
ctx.font = "30px Arial";
ctx.fillText("Key: " + key, 10, 30);
//move the box
box.move();
}
////////////////////////////////////
//key inputs here
///////////////////////////////////
window.addEventListener("keydown", function(event) {
//add event listener for key codes in here
key = event.keyCode
//change color of box when w pressed
if(key === 87){ //w
box.color = "blue";
}
if(key === 65){ //w
box.color = "yellow";
}
if(key === 68){ //w
box.color = "red";
}
if(key === 83){ //w
box.color = "green";
}
if(key === 87){ //w
//box.x = box.x +0
box.y = box.y -5
}
if(key === 65){ //a
//box.x = box.x +0
box.x = box.x -5
}
if(key === 68){ //d
//box.x = box.x +0
box.x = box.x +5
}
if(key === 83){ //s
//box.x = box.x +0
box.y = box.y +5
}
if(box.x > 500){ //s
box.y = box.y +0
box.x = box.x +0
}
if(box.y > 500){ //s
box.y = box.y +0
box.x = box.x +0
}
if(box.y>480){
box.y=480
}
if(box.y<0){
box.y=0
}
if(box.x > 480){
box.x = 480;
}
if(box.x<0){
box.x=0
}//keep it in the...