Javascript canvas 矩形动画不工作

Javascript canvas rectangle animation not working

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>

<script>
function draw() {
var ctx = document.getElementById("canvas1").getContext("2d");

// Rectangle position
var posX = 5;
var posY = 5;
ctx.fillStyle = "white";
ctx.fillRect (posX, posY, 50, 50);

document.addEventListener("keydown", function(event) {
    var key_press = String.fromCharCode(event.keyCode);
    if(key_press == "s") {
        posY += 3;
    }
 })
}
window.onload = draw;
</script>
<style>
#canvas1 {
    background: #000000;
}
</style>
</head>
<body>
<canvas id="canvas1" width="1000" height="1000"></canvas>
</body>
</html>

有人请告诉我为什么这不起作用。单击 "s" 时。将 posY 的值增加 3; 我已经有这个问题很长时间了。它与 draw(); 有什么关系吗?功能?

我不太擅长 javascript 所以我也非常感谢提示。

y value.And key_press 是大写 S 而不是 s 后,您应该更新绘图。 您还必须通过调用 clearRect

清除之前的绘图

演示 https://jsfiddle.net/3hgwp24m/1/ [更新]

document.addEventListener("keydown", function(event) {

    var key_press = String.fromCharCode(event.keyCode);
    if(key_press == "S") {//uppercase S not s
        posY += 3;
        ctx.clearRect(0, 0, canvas.width, canvas.height);//clear canvas
        ctx.fillRect (posX, posY, 50, 50);
    }
 })
}

试一试:

<html lang="en">
<head>
    <style>
       #canvas1 {
    background: #000000;
}
</style>
<meta charset="utf-8" />
<title></title>

<script>
var posX = 5;
var posY = 5;
function draw() {
var ctx = document.getElementById("canvas1").getContext("2d");

// Rectangle position
ctx.fillStyle = "white";
ctx.fillRect (posX, posY, 50, 50);

}
window.onload = draw;
    window.addEventListener("keydown", function(event) {
    var key_press = String.fromCharCode(event.keyCode);
    if(key_press == "S") {
        posY += 3;
        draw();
    }
 })
</script>
</head>
<body>
<canvas id="canvas1" width="1000" height="1000"></canvas>
</body>
</html>