Keydown上的画布矩形运动

时间:2017-06-12 19:55:59

标签: javascript canvas

我想用Canvas制作一个简单的Arkanoid游戏。一切都很好但是当我按左或右键时,我不知道如何让它移动。

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(x) {
    ctx.clearRect(x, 220, 150, 10);
}

function Keys(e) {
    switch (e.keyCode) {
        case 37:
            moveTo(x - rx);
            break;
        case 39:
            moveTo(x + rx)
    }
}

init();

这是the result

谢谢!

1 个答案:

答案 0 :(得分:0)

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();

这是正确的代码。你必须设置x变量,你必须重绘背景。