【问题标题】:Starting/Pausing canvas animation with a button click通过单击按钮启动/暂停画布动画
【发布时间】: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


    【解决方案1】:

    我通过将代码更改为此来修复它:

    StartStop.onclick = function()
    {
        if (StartStop.value == "Start")
        {
            StartStop.value = "Stop";
            var timer = setInterval(
            function()
            {
            if (StartStop.value == "Stop")
            {
                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();
            }
            else
            {
                clearInterval(timer);
            }
            },30);
        }
        else
            StartStop.value = "Start";
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多