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
var kitchen = new Image();
kitchen.src = "http://eddyinthecoffee.com/wp-content/uploads/cool-modern-kitchen-decor-with-l-shaped-brown-and-white-modular-kitchen-cabinets-combined-with-white-backsplash-and-wall-background-ideas-yellow-striped-shower-curtain-kitchen-brown-and-white-kitchen.jpg"
//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.drawImage(kitchen, 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
...