0

I want to know if it is possible to update the PIXI JS Application while the tab the canvas is on is not focused. For example, if I have a PIXI application running on one tab but then I switch to another, the PIXI application stops running. Here is some example code I took (copied from the github tutorial)

//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;
}

While focused on the tab, the cat image moves across the canvas, but when I switch to another tab, it remains in the same position until I switch back to the tab with the canvas. Is there any possible way I could make it so the cat's position is updated even when the tab is not focused?

gman
  • 100,619
  • 31
  • 269
  • 393
Ethanol
  • 370
  • 6
  • 18

1 Answers1

0

The various methods of browser animation (setTimeout, setInterval, and requestAnimationFrame) are all designed to pause if the tab is not the active tab.

There's a way to do what you're asking using a Web Worker. See the second answer to this question for an implementation: How can I make setInterval also work when a tab is inactive in Chrome?

Essentially, move app.ticker.add... into a Web Worker, and have it communicate to the tab by sending a 'tick' message every frame. That example uses setInterval instead of app.ticker (which uses requestAnimationFrame under the hood), but the idea is the same.

helloitsjoe
  • 6,264
  • 3
  • 19
  • 32