在选项卡未获得焦点时更新 PIXI JS canvas

Update PIXI JS canvas while tab is not focused

我想知道是否可以在 canvas 所在的选项卡未获得焦点时更新 PIXI JS 应用程序。例如,如果我在一个选项卡上有一个 PIXI 应用程序 运行,然后切换到另一个选项卡,PIXI 应用程序将停止 运行。这是我使用的一些示例代码(从 github 教程中复制)

//Aliases
let Application = PIXI.Application,
    Container = PIXI.Container,
    loader = PIXI.loader,
    resources = PIXI.loader.resources,
    TextureCache = PIXI.utils.TextureCache,
    Sprite = PIXI.Sprite,
    Rectangle = PIXI.Rectangle;

//Create a Pixi Application
let app = new Application({ 
    width: 256, 
    height: 256,                       
    antialias: true, 
    transparent: false, 
    resolution: 1
  }
);

//Add the canvas that Pixi automatically created for you to the HTML document
document.body.appendChild(app.view);

loader
  .add("images/cat.png")
  .load(setup);

//Define any variables that are used in more than one function
let cat;

function setup() {

  //Create the `cat` sprite 
  cat = new Sprite(resources["images/cat.png"].texture);
  cat.y = 96; 
  app.stage.addChild(cat);

  //Start the game loop 
  app.ticker.add(delta => gameLoop(delta));
}

function gameLoop(delta){

  //Move the cat 1 pixel 
  cat.x += 1;

  //Optionally use the `delta` value
  //cat.x += 1 + delta;
}

当焦点在选项卡上时,猫的图像在 canvas 上移动,但是当我切换到另一个选项卡时,它会保持在相同的位置,直到我切换回带有 [=16= 的选项卡].有什么可能的方法可以使猫的位置即使在选项卡未聚焦时也能更新吗?

浏览器动画的各种方法(setTimeoutsetIntervalrequestAnimationFrame)都是为了在选项卡不是活动选项卡时暂停。

有一种方法可以使用 Web Worker 完成您的要求。有关实现,请参阅此问题的第二个答案:How can I make setInterval also work when a tab is inactive in Chrome?

本质上,将 app.ticker.add... 移动到 Web Worker 中,并通过每帧发送 'tick' 消息让它与选项卡通信。该示例使用 setInterval 而不是 app.ticker(在后台使用 requestAnimationFrame),但想法是相同的。