【发布时间】:2020-06-05 14:02:02
【问题描述】:
我正在尝试运行一个简单的蛇游戏,该游戏默认关闭,然后单击“开始”开始。
StartStop 按钮的代码:
StartStop.onclick = function()
{
//flip the name on the button
if (StartStop.value = "Start")
{
StartStop.value = "Stop";
update();
}
else
{
StartStop.value = "Start";
clearInterval(update);
}
}
update() 中的代码启动动画:
function update()
{
setInterval(function()
{
console.log(snake.x + ", " + snake.y);
//check for collisions
//if no collisions move and draw snake
snake.x += velocity[vi][0];
snake.y += velocity[vi][1];
snake.draw();
},30);
}
我的想法是当按钮的文本值为开始时,它将文本更改为停止并调用调用 setInterval() 的 update()。 然后当你点击按钮并且文本值为Stop时,它会调用clearInterval(timer)来停止动画
我认为我没有正确使用 setInterval,关于如何让它在单击按钮时启动和停止的任何想法?
【问题讨论】:
标签: javascript canvas html5-canvas setinterval