Roman Poludnev
Roman Poludnev

Reputation: 105

PIXI.RenderTexture no render

I built a simple PIXI.js app to implement PIXI.RenderTexture, and it doesn't work.

It should render two square sprites, black and white. The black one is added with regular stage.addChild:

const sprite1 = new PIXI.Sprite(PIXI.Texture.from('bc-sq-200.png'));
sprite1.x = 500;
app.stage.addChild(sprite1);

The white one is supposed to be rendered with renderTexture:

const sprite2 = new PIXI.Sprite(PIXI.Texture.from('wt-sq-200.png'));
// app.stage.addChild(sprite2);

const renderer = PIXI.autoDetectRenderer();
const renderTexture = PIXI.RenderTexture.create({ width: 700, height: 700 });
renderer.render(sprite2, { renderTexture });

const mainSprite = PIXI.Sprite.from(renderTexture);
app.stage.addChild(mainSprite);

However, only the black square can be seen.

What could be the problem? What is going wrong?

Minimal example Github repo: https://github.com/poludnev/test-pixi-render-texture

Upvotes: 3

Views: 972

Answers (1)

Sam Spade
Sam Spade

Reputation: 1486

Fixed it. I think it's a problem with the autodetect renderer option, you can simply use the renderer from the app instead and that should work:

let app = new PIXI.Application({
  width: 500,
  height: 256,
  antialiasing: true,
  transparent: false,
  resolution: 1
});

document.body.appendChild(app.view);

//To change the background color
app.renderer.backgroundColor = "0xff0000";
const sprite1 = new PIXI.Sprite(PIXI.Texture.from("public/bc-sq-200.png"));

app.stage.addChild(sprite1);
const sprite2 = new PIXI.Sprite(PIXI.Texture.from("public/wt-sq-200.png"));

sprite2.position.x = 0;
sprite2.position.y = 0;
sprite2.anchor.x = 0;
sprite2.anchor.y = 0;

setTimeout(() => {
  const renderTexture = PIXI.RenderTexture.create({ width: 200, height: 200 });
  console.log(renderer);

  app.renderer.render(sprite2, {
    renderTexture
  });
  const mainSprite = new PIXI.Sprite(renderTexture);
  mainSprite.x = 200;
  mainSprite.y = 0;
  mainSprite.width = 200;
  mainSprite.height = 200;
  app.stage.addChild(mainSprite);
  console.log(mainSprite);
}, 2000);

Here is a demo

Some other stuff I changed to minimize potential problems:

  1. The setTimeout means that the png has enough time to load. You should ensure you pre-load assets, the setTimeout was just because it's easy.

  2. Width and height for mainSprite are important

  3. added a red background so you could more easily see the two boxes.

I really thought this would be a 10 second fix, but this legit took me an hour or two. Definitely needs better documentation to make the relationship between autoDetectRenderer and RenderTexture more clear, since OPs original code was almost straight from the docs.

Upvotes: 3

Related Questions