User Input

by soggydoughnut54

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

//variables for rectangles
var speed = 0;
var key = 38;
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;
  }
}

/***********
function for drawing stuff
************/
function draw() {
    //color for the background
    ctx.fillStyle = "red";
    //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
 //capture event key code
  key = event.keyCode
  //change the color of box with key
  if(key ===87) {
  box.color = "blue";
  }
  //growbox with s
  if(key ===83){
  box.width = box.width * 2;
  box.height = box.height * 2
  }
  //shrink box
  if(key ===80){
  box.width = box.width * 0.5
  box.height = box.height * 0.5
  }
  // move left
  if(key ===37){
  box.x = box.x -20
  }
  // move up
    if(key ===38){
  box.y = box.y -20
  }
  // move right
    if(key ===39){
  box.x = box.x +20
  }
  //move down
    if(key ===40){
  box.y = box.y +20
  }
// 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
 
//...