the Sprite fails to appear on the screen

Can you help me figure out how to fix the issue I'm having with loading images in this component? Currently, when I refresh the page, the image does not load properly and appears resized to 1 pixel width. Should I wait for the image to fully load before resizing it? If so, how can I achieve that?

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();
  }

}

Answer №1

One issue that was causing problems was the canvas resizing before the image finished loading. Here is the solution:

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

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

function setup() {

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

  const width = image.width;
  const height = image.height;

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

  // Adjustment for maintaining aspect ratio:
  app.renderer.resize(width, height);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to verify if the database has been successfully saved and the API call has been

I am currently in the process of developing a function that calls two other functions. Function 1 is responsible for saving an object to a database, while function 2 performs an API call. async createMSCalendarEntry(start: Date, end: Date, name: string ...

Tips for transferring data from an Angular @Input property to another variable and displaying it in a child component

I am dealing with the following parent HTML structure: <p>Parent</p> <app-child [mainData]="mainData"></app-child> In parent.ts, I have the following code: mainData = []; ngOnInit() { this.myService((res)=>{ this.mainData = ...

Is it preferable to place my http services in the core folder as singletons, or within the lazy loaded modules themselves within Angular?

(React) Is it more advisable to store my http services in a core folder (as singleton) or within the lazy loaded modules themselves? What is the recommended approach? ...

Enhance the API response for Angular service purposes

I am currently working on modifying the response returned by an API request. At the moment, I receive the response as: [ { name: "Afghanistan" }, { name: "Åland Islands" } ] My goal is to adjust it to: [ { name: "A ...

It seems like there is an issue with your network connection. Please try again

Recently, I made the switch to EndeavourOS, which is based on Archlinux. I completed all my installations without any issues and attempted to create a new NestJs project after installing NVM, Node's latest version, and the NestJs/cli. However, when I ...

Is React Context malfunctioning due to a syntax error?

Using the function "login" from React context is causing an error for me: const handleLogin = async (data: LoginType) => { try { await login(auth, data.email, data.password); router.push("/Dashboard"); } catch (error: an ...

What is the best way to convert a JSON string received from Angular into a Java Object within a Spring

I am currently utilizing WebSocket to create a chat application. Below is the code from my Angular application that sends a MessageModel object to the backend after converting it into a JSON string: sendMessage(message: MessageModel){ let data = JSON.str ...

Is Angular2 the Perfect Fit for Custom HTML Webresources in Dynamics CRM 2016?

Has anyone experimented with integrating Angular2 for custom webresource development in Dynamics CRM 2016? I searched for resources but only came across tutorials on using AngularJS, such as this one ...

Integrating router-outlet into Angular 2 component affects ngModel functionality

Currently, I am experimenting with angular 2 beta 9 and have encountered an issue that I would like some help with. In my component, I have bound an input field using the following code: [(ngModel)]="email" (ngModelChange)="changedExtraHandler($event)" ...

Merging two arrays that have identical structures

I am working on a new feature that involves extracting blacklist terms from a JSON file using a service. @Injectable() export class BlacklistService { private readonly BLACKLIST_FOLDER = './assets/data/web-blacklist'; private readonly blackl ...

Experiencing template parsing errors in Angular 2+ unit tests with Karma and Jasmine

Encountering problems with running Angular tests on certain components, even though they function properly in production. Seeing the following error message: Failed: Template parse errors: 'app-date-picker' is not a recognized element: 1. Ensure ...

What is the most efficient way to remove all typed characters from fields when clicking on a different radio button? The majority of my fields share the same ngModel on a separate page

Is there a way to automatically clear all typed characters in form fields when switching between radio buttons with the same ngModel on different pages? I noticed that the characters I type in one field are retained when I switch to another radio button. ...

The extended class possesses a distinct type from the base class, which is reinforced by an interface

Is it possible to write a method that is an extension of a base class, but with a different return type, if supported by the shared interface, without adding a type declaration in class 'a'? In practical terms, classes a & b exist in JavaScript ...

Experiencing difficulty in retrieving data streams in Angular 5 when using the pptxGenjs library

I am working on incorporating images into a PowerPoint file using pptxGenjs in Angular5. While I have successfully retrieved the file with content, my goal is to extract the data from the PowerPoint file in base64 or a similar output format. However, all ...

How can I generate pure JavaScript, without using Typescript modules?

Take this scenario as an example ... index.ts import { x } from "./other-funcs"; function y() { alert("test"); } x(y); other-funcs.ts import { z } from "some-module"; export function x(callback: () => void): void { z(); callback(); } ...

Sinon Stub generates varying values with each invocation

I'm pretty new to TypeScript and JavaScript, but I've managed to create a functioning VScode extension that I'm really happy with. However, I'm running into some issues with my Mocha tests. Here's a snippet of the code I'm str ...

Ways to showcase my select/option in Angular 14?

My select input is not displaying and I'm struggling to understand why. Despite seeing it in the inspector, it remains hidden... I initially attempted to retrieve data from my service, which failed. Then, I experimented with placing static data direc ...

Eliminate any repeated elements in the array by utilizing TypeScript

Hey, I'm trying to figure out how to remove duplicate entries from an array where the UserId values are the same, and keep only one of each unique entry. Can anyone help me with this? For example: a=[ {userId:1,name:''}, {userId:2,name:&apo ...

Tips on incorporating dynamic expressions within ngFor loops?

Is there a way to dynamically display specific properties from objects in an array (list: any[]) within an *ngFor loop in Angular? I am currently working on a component called ListComponent that is responsible for rendering a list of items. The parent com ...

Error: Trying to modify an immutable property 'title' of object '#<Object>' - React JS and Typescript

Whenever I press the Add button, all input values are stored in a reducer. However, if I append any character to the existing value in the input fields, it triggers the following error: Cannot assign to read only property 'title' of object &apos ...