Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/408.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 画布矩形在向下键上移动_Javascript_Canvas - Fatal编程技术网

Javascript 画布矩形在向下键上移动

Javascript 画布矩形在向下键上移动,javascript,canvas,Javascript,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"); drawP

我想用画布做一个简单的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();
这是

谢谢

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变量,并且必须重新绘制背景

这是正确的代码。您必须设置x变量,并且必须重新绘制背景