Javascript画布矩形动画无法正常工作

时间:2016-06-27 18:25:47

标签: javascript animation canvas keyevent

<!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不是很擅长,所以我也非常感谢提示。

2 个答案:

答案 0 :(得分:1)

您应该在更改y值后更新图形。key_press大写S而不是s。 您还必须通过调用clearRect

清除上一张图

demo 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);
    }
 })
}

答案 1 :(得分:0)

试一试:

<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>