xF4B xF4B -4 years ago 77
Javascript Question

Canvas Rectangle Movement On Keydown

I want to make a simple Arkanoid Game with Canvas. Everything is ok but when I press left or right key, i don't know how to make it move.
This is the jsfiddle:

jsfiddle.net/89rr8qmc

Thanks!!

Answer Source
var c = document.getElementById("game");
var ctx = c.getContext("2d");
document.addEventListener("keydown", Keys);
var x = 180;
var rx = 10;

function init() {
    drawBackground("#000000");
    drawPlayer();
}

function drawBackground(color) {
    ctx.fillStyle = color;
    ctx.fillRect(0, 0, 500, 250);
}

function drawPlayer() {
    ctx.fillStyle = "red";
    ctx.fillRect(x, 220, 150, 10);
}

function moveTo(xP) { // changed parameter name
    x = xP; // update variable x
    init(); // redraw background and player
}

function Keys(e) {
    switch ((e.keyCode || e.which)) { // some browsers use e.which
        case 37:
            moveTo(x - rx);
            break;
        case 39:
            moveTo(x + rx)
    }
}

init();

This is the correct code. You have to set the x variable and you have to redraw the background.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download