0

我有一个滑动的图片沿着屏幕缓慢移动。一旦他们离开屏幕,他们就会回到功能区的后面。因此,当您在网页上但当您离开并且其中一张图像超出范围时,一切正常。它会被放回错误的地方。我认为这可能与 requestAnimationFrame 有关,但我不知道是什么原因造成的。

function tick(timePassed)
{
//dont worry about it
area.tick();
//updates the imgs X position
for (var i = 0; i < loadedImgs.length; i++)
{
    loadedImgs[i].x -= (timePassed * 10) / 1000;
    if (loadedImgs[i].x + loadedImgs[i].width <= 0)
    {
        loadedImgs[i].x = totalLength - loadedImgs[i].width;
    }
}
//updates there y position based on scroll wheel
dy -= dy * .1;
y += dy / 10;



}

缓冲功能

//buffer function
function update()
{

buffer.clearRect(0, 0, width, 600);
area.draw();//this has nothing to do with what going on
if (showAlert)//checks to see if a message is needed
{
    buffer.font = "30px monospace";
    var strings = alertMessage.split(" ");
    var charCount = 0;
    var line = 0;
    for(var i =0;i<strings.length;i++)
    {
        buffer.fillText(strings[i], (width / 5) + (charCount* letterSize), 300 + (line * 30));
        if (Math.floor(charCount/50) > 0)
        {
            line++;
            charCount = 0;
        }
        else
        {
            charCount += strings[i].length + 1;
        }

    }

}
else
{
    //paints all imgs
    for (var i = 0; i < loadedImgs.length; i++)
    {
        buffer.drawImage(loadedImgs[i].obj, loadedImgs[i].x, y);
    }
}
//dont worry about it
buffer.drawImage(area.canvas, (width / 2) - (area.width / 2), y + 1000);
//calls the render
render();

}

渲染函数

    function render()
    {
          //paints to main canvas
          ctx.clearRect(0, 0, width, 600);
          ctx.drawImage(b, 0, 0);
    }

保持时间

function renderLoop(time)
{
    var timePassed = time - lastRender;
    if (timePassed < 33) { window.requestAnimationFrame(renderLoop); return; }
     window.requestAnimationFrame(renderLoop);
     lastRender = time;
     tick(timePassed);
     update();

  }
4

1 回答 1

2

requestAnimationFrame当其浏览器选项卡失去焦点时将停止,因此当焦点返回时,您的时间renderLoop比您预期的要大得多。

这会导致 renderLoop 假设已经过去了更长的时间,并且正在放弃您的重新定位。

于 2016-07-24T20:25:55.573 回答