/*************
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 speedy = 0;
var key = -1;
var box = {
//variables that define the box
color:"black",
x:240,
y:240,
width:20,
height:20,
//function that tells the box to move
move:function(){
this.x = this.x+speed;
this.y = this.y+speedy;
}
}
/***********
function for drawing stuff
************/
function draw() {
//color for the background
ctx.fillStyle = "maroon";
//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;
if(key===65){
speed = -10;
if (box.x >= 480)
speed = 0;
}
key = event.keyCode;
if(key===68){
speed = 10;
}
key = event.keyCode;
if(key===87){
speedy = -10;
}
key = event.keyCode;
if(key===83){
speedy = 10;
}
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
key = event.keyCode;
if(key===68){
speed = 0
}
key = event.keyCode;
if(key===65){
speed = 0
}
key = event.keyCode;
if(key===87){
speedy = 0
}
key = event.keyCode;
if(key===83){
speedy = 0
}
// Consume the event so it doesn't get handled twice
event.preventDefault();
},...
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.