0
为什么按下箭头键时第二个正方形会消失? 而不是消失第二个广场应该是第一个广场。我检查了每行代码,没有发现任何错误,我使用的浏览器是Google Chrome。为什么第二个正方形消失
这里是我的代码:
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id="canvas" style="border:1px solid #000;"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = 500;
var height = 500;
var win = false;
var player = {
x:250,
y:250,
speed:5,
width:100,
height:100
};
var ai = {
x:150,
y:150,
mox:0,
moy:0,
speed:1,
width:50,
height:50
};
canvas.width = width;
canvas.height = height;
ctx.fillRect(player.x, player.y, player.width, player.height);
ctx.stroke();
ctx.fillRect(ai.x, ai.y, ai.width, ai.height);
ctx.stroke();
function a() {
if(player.x < ai.x && win==false) {
ai.mox-=ai.speed;
}
if(player.x > ai.x && win==false) {
ai.mox = ai.speed;
}
if(player.y < ai.y && win==false) {
ai.moy -= ai.speed;
}
if(player.y > ai.y && win==false) {
ai.moy = ai.speed;
}
canvas.width = canvas.width;
var ctx = canvas.getContext("2d");
ctx.fillRect(ai.x, ai.y, ai.width, ai.height);
ctx.stroke();
}
function move(e) {
// alert(e.keyCode);
if(e.keyCode==37) {
player.x -= player.speed;
}
if(e.keyCode==39) {
player.x += player.speed;
}
if(e.keyCode==38) {
player.y -= player.speed;
}
if(e.keyCode==40) {
player.y+=player.speed;
}
ai.x += ai.mox;
ai.y += ai.moy;
a();
canvas.width = canvas.width;
var ctx = canvas.getContext("2d");
ctx.fillRect(player.x, player.y, player.width, player.height);
ctx.stroke();
}
document.onkeydown = move;
</script>
</body>
</html>
请告诉我什么是错我的代码。另外一个语法检查器告诉我它在语法上是正确的。
请格式化您的代码,因此它实际上是人类可读的。那么我们可能会帮助你。 – MarthyM