requestAnimationFrame 表现奇怪,图像在屏幕外移动

requestAnimationFrame behaving weird with images moving while off screen

我有一张滑动图片沿着屏幕慢慢移动。一旦他们离开屏幕,他们就会回到色带的背面。因此,当您在网页上时一切正常,但当您离开并且其中一张图片超出范围时。它会放回错误的地方。我认为这可能与 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();

  }

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

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