User Input

by Starsavior

HTML

<canvas width="500" height="500" id="myCanvas"></canvas>000

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

//variables for rectangles
var speed = 0;
var key = -1;
var box = {
//variables that define the box
	color:"green",
	x:240,
  y:240,
  width:20,
  height:20,
  //function that tells the box to move
  move:function(){
  	this.x = this.x+speed;
  }
}

/***********
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
//captture event key code
key = event.keyCode;
//change box color with 'w' key
if (key === 38){// up
box.location(box.y = box.y - speed)
}
if (key === 40){// down
box.location(box.y = box.y + speed)
}
if (key === 39){// up
box.location(box.x = box.x + speed)
}
if (key === 37){// up
box.location(box.x = box.x - speed)
}
if (key === 32){// up
speed = speed + 1
}
if (key === 16){
speed = speed - 1
}
if(key === 82){// r
box.color = "red"
}
if(key === 69){//e
box.color = "green"
}
// Consume the event so it doesn't get handled twice
  event.preventDefault();
}, true);
///////////////////////////////////////
//try to see if you can do it on key up
///////////////////////////////////////
window.addEventListener("keyup", function(event) {
 //add event listener for key codes in here
 
// Consume the event so it doesn't get handled twice
 ...