javascript - 按键时 Canvas 矩形运动

标签 javascript canvas

我想用 Canvas 制作一个简单的打砖 block 游戏。一切正常,但是当我按左键或右键时,我不知道如何让它移动。

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 .

谢谢!

最佳答案

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

关于javascript - 按键时 Canvas 矩形运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44507713/

相关文章:

Javascript:当机器时间不正确时,是否有可能获得当前的 Unix 时间戳?

html - threejs Canvas todataurl 是空白的

javascript - 如何绘制在 html5 Canvas 上非常接近的 x 轴和 y 轴的坐标?

python - Tkinter - Canvas 滚动/滚动区域解释 - (非)限制区域

javascript - getImageData内存泄漏?

javascript - 多个指令的执行顺序是什么?

php - 如何根据数据库下拉列表的 mysql 计数来限制或停止表单提交?

Javascript,为什么被视为八进制

php - 检查 Facebook 是否被阻止然后重定向

Javascript Canvas 简单光源