requestAnimationFrame 行为怪异,图像在屏幕外移动时

问题描述 投票:0回答:1

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

  }
javascript canvas requestanimationframe
1个回答
2
投票
当浏览器选项卡失去焦点时,

requestAnimationFrame
将停止,因此当焦点返回时,您在
renderLoop
中的时间比您预期的要长得多。

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

© www.soinside.com 2019 - 2024. All rights reserved.