the Sprite does not load

Viewed 35

I need to implement this component to load the image when the new url provided. the problem by my current implementation is that when I refresh the page the image does not load during debugging I found out that the sprite(here pic) in the beginning has pic.width = 1 therefore the image resized to 1 and does not show. do you know how can I fix this? should I wait the pic to be loaded then resize? how ?

export class ImageComponent implements OnChanges {

  @Input() urlInputImage: string;
  public app: PIXI.Application;
  constructor() {
  }

  ngOnChanges() {
    this.drawImage();
  }

  private removeAllChildNodes(parent) {
    if (parent.firstChild) {
      parent.removeChild(parent.firstChild);
    }
  }

  private drawImage(): void {
    const frame = document.querySelector('#frame');
    this.removeAllChildNodes(frame);
    this.app = new PIXI.Application({
      backgroundColor: 0xffffff,
    });

    const container = new PIXI.Container();
    this.app.stage.addChild(container);
    const texture = PIXI.Texture.from(this.urlInputImage);
    const pic = new PIXI.Sprite(texture);
    container.addChild(pic);

    document.getElementById('frame').appendChild(this.app.view);
    this.resize(pic);

  }


  private resize(pic) {
  const w = pic.width;
  const h = pic.height;

  //this part resizes the canvas but keeps ratio the same
  this.app.renderer.view.style.width = w + "px";
  this.app.renderer.view.style.height = h + "px";

  //this part adjusts the ratio:
    this.app.renderer.resize(w,h);
  }

  destroy() {
    this.app.destroy();
  }
  ngOnDestroy(): void {
    this.destroy();
  }

}
1 Answers

yeah the problem was that the canvas gets resized before the image has loaded! here is the solution:

private drawImage(): void {
PIXI.Loader.shared.reset();
const frame = document.querySelector('#frame');
const url = this.urlInputImage;
this.removeAllChildNodes(frame);
const app = new PIXI.Application({
  backgroundColor: 0xffffff,
});

PIXI.Loader.shared
  .add('layout',url)
  .load(setup);

function setup() {

  const pic = new PIXI.Sprite(PIXI.Loader.shared.resources.layout.texture);
  app.stage.addChild(pic);

  const w = pic.width;
  const h = pic.height;

  app.renderer.view.style.width = w + "px";
  app.renderer.view.style.height = h + "px";

  //this part adjusts the ratio:
  app.renderer.resize(w,h);
}
Related