// canvas and context references
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillRect(100, 100, 50, 30);
var width = c.width;
var height = c.height;
console.log(c);
// so enjoy2 does only send one keydown
// for a continious keypress
// when you hold a key on the keyboard
// it fires multiple keydowns...
// hm can a timeout here simulate this
// behaviour?!
window.addEventListener("keydown", doKeyDown, true);
window.addEventListener("keyup", doKeyUp, true);
function doKeyUp(e) {
console.log("keyup", e.keyCode);
}
var x = 100;
var y = 100;
function doKeyDown(e) {
console.log("keydown", e.keyCode);
//====================
// THE W KEY or UP
//====================
if (e.keyCode == 87 || e.keyCode == 38) {
clearCanvas();
y = y - 10;
ctx.fillRect(x, y, 50, 30);
}
//====================
// THE S KEY or DOWN
//====================
if (e.keyCode == 83 || e.keyCode == 40) {
clearCanvas();
y = y + 10;
ctx.fillRect(x, y, 50, 30);
}
//====================
// THE A KEY or LEFT
//====================
if (e.keyCode == 65 || e.keyCode == 37) {
clearCanvas();
x = x - 10;
ctx.fillRect(x, y, 50, 30);
}
//====================
// THE D KEY or RIGHT
//====================
if (e.keyCode == 68 || e.keyCode == 39) {
clearCanvas();
x = x + 10;
ctx.fillRect(x, y, 50, 30);
}
}
function clearCanvas() {
c.width = c.width;
}
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.