gpt4 book ai didi

javascript - 如何在 JS 中使 Canvas 无限用于无限跑酷类型的游戏

转载 作者:行者123 更新时间:2023-12-03 01:37:10 24 4
gpt4 key购买 nike

我希望 HTML5 Canvas 永远不会结束,这样正方形就永远不会停止移动,它会继续“运行”,这样它就可以跳过障碍并增加分数等等。我真的不知道该怎么做。请提前提供帮助并致谢。我把我的代码贴在下面给大家看,我把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>

最佳答案

如果您希望 block 无限地“向前”运行,则需要使 Canvas 上的所有其他对象向后移动。当然,要执行此操作,您需要添加另一个对象以供引用。

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

关于javascript - 如何在 JS 中使 Canvas 无限用于无限跑酷类型的游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51015584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com