简体   繁体   English

如何为JS中的无限跑步者类型的游戏制作画布

[英]How do I make the canvas endless for an infinite runner type of game in JS

I want the HTML5 canvas to never end so that the square never stops moving, it keeps on "running" so that it can jump over obstacles and the score increases etc. I really do not know how to do this. 我希望HTML5画布永远不会结束,以便正方形永远不会停止移动,它会一直保持“运行”状态,以便它可以跳过障碍物并提高得分等。我真的不知道该怎么做。 Please help and thanks in advance. 请帮助并提前致谢。 I have posted my code below for everyone to see, I incorporated the JS into the HTML, yep. 我在下面发布了我的代码,以供大家查看,是的,我将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>

You need to make every other object on the canvas move backward if you want your block to run endlessly "forward." 如果要让块无休止地“向前”运行,则需要使画布上的所有其他对象向后移动。 Of course, to do this you would need to add another object for reference. 当然,要执行此操作,您需要添加另一个对象以供参考。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM