单击按钮开始/暂停画布动画

时间:2020-02-21 06:59:51

标签: javascript canvas html5-canvas setinterval

我正在尝试运行一个简单的蛇游戏,该游戏默认情况下处于关闭状态,然后单击“开始”开始。

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);
}

我的想法是,当按钮的文本值为Start时,它将文本更改为Stop并调用update(),后者调用setInterval()。 然后,当您单击按钮并且文本值为Stop时,它将调用clearInterval(timer)来停止动画

我认为我没有正确使用setInterval,关于如何启动和停止按钮单击有任何想法吗?

1 个答案:

答案 0 :(得分:0)

我通过将代码更改为此来解决它:

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";
}