如何在html5中连续移动一行?

时间:2016-09-17 23:27:51

标签: javascript jquery html html5 canvas

我是HTML 5和JavaScript新手。我打算在画布上自动移动一行,直到我按下停止按钮。到目前为止,我已经找到了一个示例,展示了如何连续移动线。我试图在此示例中添加停止按钮功能。

然而,线路自动停止移动。相反,每当我按下停止时它会移动一点点。为了找到错误,我检查了我的开发者控制台。控制台建议已超出最大调用堆栈大小。

此外,我计划有两个可以上下移动线路的按钮是否可能?如果是,应该传递一个不同的点数组来绘制函数。例如,如果有人点击左边,我应该传递一个新的数组,其中x坐标是固定的,但是y正在增加?

我有以下代码:

MyCol <- topo.colors(20)
barplot(rep(1,20), yaxt="n", col=MyCol)
x <- 1:20
MyLab <- paste("Zone",x)
legend("bottom",MyLab,fill=MyCol,horiz=T)

1 个答案:

答案 0 :(得分:0)

您的问题是您调用requestAnimationFrame ..

的地方

你有

requestAnimFrame(draw(runAnimation));

draw(runAnimation)正在调用并运行函数draw,该函数然后向下运行同一行并执行相同的操作,函数永远不会有机会退出并最终调用堆栈溢出。

要修正将行更改为

requestAnimationFrame(draw); 

现在你只是将referance传递给函数draw。

如果您希望传递runAnimation值,则无法使用requestAnimationFrame执行此操作,因为它已经将参数传递给draw函数。 (时间)

对于这种情况,您只需从

更改函数声明即可
function draw(runAnimation) {  // runAnimation holds the time as that
                               // is what requestAnimationFrame will
                               // pass as the first argument

将其更改为

function draw(time){ // you can ignore the time as you don't need it

变量runAnimation仍可在函数内部看到,因为您已在同一范围内定义它。

最后一次更改是停止事件

    stop.addEventListener('click', function () {
        runAnimation.value = !runAnimation.value;

        if (runAnimation.value) {
            requestAnimationFrame(draw(runAnimation)); // You are calling
                                                       // draw, but you 
                                                       // should just pass
                                                       // a reference.
        }
    });

    stop.addEventListener('click', function () {
        runAnimation.value = !runAnimation.value;

        if (runAnimation.value) {
            requestAnimationFrame(draw);  // only the function reference is
                                          // needed.
        }
    });
相关问题