我希望HTML5画布永远不会结束,以使正方形永远不会停止移动,它会一直保持“运行”状态,从而可以跳过障碍物并提高得分等。我真的不知道该怎么做。请帮助并提前致谢。我在下面发布了我的代码,供大家查看,是的,我将JS合并到HTML中。
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
<title>Move Square</title>
</head>
<body>
<div id="centre">
<canvas id="myCanvas" height="100px" width="200px"></canvas>
</div>
<script>
function draw(){
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.fillStyle = "grey";
ctx.fillRect(0,0,300,300);
ctx.fillRect(0,0,300,300);
ctx.closePath();
x+=dx/4;
//Draw Square
ctx.fillStyle = "red";
ctx.fillRect(x,y,20,20);
clearRect(0, 0, canvas.width, canvas.height);
}
var x = 20;
var y = 20;
var dx = 5;
var dy = 5;
setInterval(draw,10);
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 39) {
x+=dx;
}
}
</script>
</body>
</html>
答案 0 :(得分:1)
如果希望块连续“向前”运行,则需要使画布上的所有其他对象向后移动。当然,要执行此操作,您需要添加另一个对象以供参考。
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
<title>Move Square</title>
</head>
<body>
<div id="centre">
<canvas id="myCanvas" height="100px" width="200px"></canvas>
</div>
<script>
function draw(){
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.fillStyle = "grey";
ctx.fillRect(0,0,300,300);
ctx.fillRect(0,0,300,300);
ctx.closePath();
//Draw Square
ctx.fillStyle = "red";
ctx.fillRect(x,y,20,20);
//Two extra green squares
ctx.fillStyle = "green";
ctx.fillRect(x2,50,20,20);
ctx.fillRect(x3,50,20,20);
//make them move backwards at the same speed
x2 -= dx/4;
x3 -= dx/4;
}
var x = 20;
var y = 20;
var dx = 5;
var dy = 5;
//X coordinates for green blocks:
var x2 = 50;
var x3 = 250;
setInterval(draw,10);
document.addEventListener("keydown", keyDownHandler, false);
//document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 39) {
x+=dx;
}
}
</script>
</body>
</html>