<!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 值后更新绘图。并且 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);
}
})
}
关于Javascript Canvas 矩形动画不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38060750/