Canvas and keyboard

Canvas with pure JavaScript

by Denise Nepraunig

HTML

<canvas id="myCanvas" width="500" height="400" style="border:1px solid #000000;"></canvas>

JavaScript

// 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;
}