/*************
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
//...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.