When a child is added to a pixi.js sprite, it causes the child's size and position to become

Using typescript and pixi.js v4.8.2, I have implemented the following code to create containers:

    let appWidth = app.renderer.view.width
    let appHeight = app.renderer.view.height
    mapContainer = new PIXI.Sprite(PIXI.loader.resources.water_pattern.texture);
    mapContainer.height = app.renderer.view.height
    mapContainer.width = appWidth - appWidth / 5 - appWidth / 14
    mapContainer.x = app.renderer.view.width / 14

    cardContainer = new PIXI.Sprite(PIXI.Texture.WHITE);
    cardContainer.tint = 0x3C2415;
    cardContainer.height = app.renderer.view.height / 2
    cardContainer.width = app.renderer.view.width / 14

    actionContainer = new PIXI.Sprite(PIXI.Texture.WHITE);
    actionContainer.tint = 0x00FF00;
    actionContainer.height = app.renderer.view.height / 2
    actionContainer.width = app.renderer.view.width / 14
    actionContainer.y = app.renderer.view.height / 2

    chatContainer = new PIXI.Sprite(PIXI.Texture.WHITE);
    chatContainer.tint = 0x008080;
    chatContainer.height = app.renderer.view.height / 2
    chatContainer.width = app.renderer.view.width / 5
    chatContainer.x = app.renderer.view.width * 4 / 5

    playerContainer = new PIXI.Sprite(PIXI.Texture.WHITE);
    playerContainer.tint = 0xCCCCCC;
    playerContainer.height = app.renderer.view.height / 2
    playerContainer.width = app.renderer.view.width / 5
    playerContainer.y = app.renderer.view.height / 2
    playerContainer.x = app.renderer.view.width * 4 / 5

    app.stage.addChild(mapContainer, cardContainer, actionContainer, chatContainer, playerContainer)

Next, I attempted to create sprites within these containers:

    let settlement = new PIXI.Sprite(PIXI.loader.resources.settlement_red.texture)
    settlement.height = 10
    settlement.width = 10
    settlement.x = 0
    settlement.y = 0
    chatContainer.addChild(settlement)

However, the output does not match the expected result:

https://i.sstatic.net/FE13y.png

The positioning and size of the house sprite appear incorrect. What could be causing this issue and how can it be resolved?

It should be noted that despite the option to use PIXI.Container, I prefer using sprites for background images within containers. I believe it provides a better structure for integrating background images directly into the container.

Finally, here is a snippet of my application code:

    app = new PIXI.Application({ // http://pixijs.download/release/docs/PIXI.Application.html
            antialias: true,    // default: false
            forceCanvas: true, // default: false (forces canvas rendering instead of webgl rendering)
        }
    );
    app.renderer.autoResize = true;
    app.renderer.view.style.position = "absolute";
    app.renderer.view.style.display = "block";
    app.renderer.autoResize = true;
    app.renderer.resize(window.innerWidth, window.innerHeight);
    document.body.appendChild(app.view);

Answer №1

This valuable insight was shared by Ivon in a discussion on this forum.

An enduring issue that has plagued PixiJS for quite some time, with roots even in Flash!

The problem can be summarized as follows:

  1. The width and height properties are not reliable and have their quirks. https://github.com/pixijs/pixi.js/wiki/v4-Gotchas#width-and-height-are-evil

  2. Changing behavior is hindered due to compatibility issues with Flash. https://github.com/pixijs/pixi.js/blob/dev/src/core/display/Container.js#L570

One workaround is to modify the Sprite class by overriding the getLocalBounds method to disregard children, keeping only the essential code inside the "if" condition. See details here: https://github.com/pixijs/pixi.js/blob/dev/src/core/sprites/Sprite.js#L373

To tackle the issue, I switched from using PIXI.Sprite to PIXI.Container

export class ViewContainer extends PIXI.Container {
    bg: PIXI.Sprite

    constructor(x: number, y: number, w: number, h: number, color: number, container: Container) {
        super()
        this.x = x
        this.y = y
        this.bg = new PIXI.Sprite(PIXI.Texture.WHITE)
        this.bg.tint = color
        this.bg.width = w
        this.bg.height = h
        this.addChild(this.bg)
        container.addChild(this)
    }

    addBorder() {
        let border = new PIXI.Graphics();
        border.lineStyle(.1,0xFFFFFF,1);
        border.drawRect(0,0,10,10);
        border.endFill();
        this.bg.addChild(border)
    }
}

Below is the setup for creating containers:

function createContainers() {
    let appW = app.renderer.view.width
    let appH = app.renderer.view.height

    cardContainer = new ViewContainer(0, appH*10/11, appW*2/5, appH/11, 0x3C2415, app.stage)
    actionContainer = new ViewContainer(appW*2/5, appH*10/11, appW*2/5, appH/11, 0x00FF00, app.stage)
    chatContainer = new ViewContainer(appW*4/5, 0, appW/5, appH/2, 0x008080, app.stage)
    playerContainer = new ViewContainer(appW*4/5, appH/2, appW/5, appH/2, 0xCCCCCC, app.stage)
    mapContainer = new ViewContainer(0, 0, appW - appW/5, appH*10/11, 0x0000FF, app.stage)
}

This approach allows for precise positioning of objects with code such as:

let settlement = new PIXI.Sprite(PIXI.loader.resources.settlement_red.texture)
settlement.height = 10
settlement.width = 10
settlement.x = 0
settlement.y = 0
chatContainer.addChild(settlement)

https://i.sstatic.net/w56GT.png

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

The error message states that the property "user" is not found in the type "Session & Partial<SessionData>"

I recently had a javascript code that I'm now attempting to convert into typescript route.get('/order', async(req,res) => { var sessionData = req.session; if(typeof sessionData.user === 'undefined') { ...

Struggling to Enforce Restricted Imports in TypeScript Project Even After Setting baseUrl and resolve Configuration

I am facing challenges enforcing restricted imports in my TypeScript project using ESLint. The configuration seems to be causing issues for me. I have configured the baseUrl in my tsconfig.json file as "src" and attempted to use modules in my ESLint setup ...

Using TypeScript to deserialize JSON into a Discriminated Union

Consider the following Typescript code snippet: class Excel { Password: string; Sheet: number; } class Csv { Separator: string; Encoding: string; } type FileType = Excel | Csv let input = '{"Separator": ",", "Encoding": "UTF-8"}&ap ...

Is it feasible to update just one key within an exported type using setState in TypeScript?

Recently, I decided to dive into Typescript within my React App and encountered an error that has left me stumped. I'm wondering if it's possible to access a specific key in an exported type and modify its value? Here is how I've exported ...

What is the best way to utilize moment.js for adding days while excluding weekends?

I have a requirement to set a default follow-up date that is two days ahead of the current date. The existing code for this functionality is as follows: const Notify = moment().add(2, 'days').toDate(); Now, I need to modify this code to exclude ...

Resolving ES6 type conflicts while compiling TypeScript to Node.js

I seem to be facing some challenges with the TypeScript 2 type system when working with Node.js. Let me explain the situation: I am compiling a small Node.js Express server written in TypeScript to plain ES5 for running under Node 6.10.0 (target: ES5 in ...

Issues with concealing the side menu bar in Vue.js

I've been attempting to conceal the side menu bar, with the exception of the hamburger icon when in the "expanded" state. Despite my efforts to modify the CSS code, I am still struggling to hide the small side menu bar. The following images represent ...

Is there a more effective alternative to using the ternary condition operator for extended periods of time?

Do you know of a more efficient solution to handle a situation like this? <tr [style.background]="level == 'ALARM' ? 'violet' : level == 'ERROR' ? 'orange' : level == 'WARNING' ? 'yellow' ...

In Angular2, declaring variables with log={} and dynamically adding log details like [{id: "Logs List Details1"}, {id: "Logs List Details2"}] is a simple process

When declaring a variable with log = [{id: "Logs List Details1"},{id: "Logs List Details2"},....etc}] dynamically, issues arise when pushing dynamic data to it. If the data is static and pushed incrementally, it exceeds the page limit. However, if only one ...

"Benefit from precise TypeScript error messages for maintaining a streamlined and organized architecture in your

As I dip my toes into the world of functional programming with typescript for a new project, I am encountering some challenges. In the provided code snippet, which follows a clean architecture model, TypeScript errors are popping up, but pinpointing their ...

Advanced Angular2 Services Expansion

I'm looking to enhance an existing angular service (for example, Http). Requirements: The extension of the service should be done through angular's dependency injection It should be possible to extend the service multiple times using a pattern ...

Caught up: TypeScript not catching errors inside Promises

Currently, I am in the process of developing a SPFx WebPart using TypeScript. Within my code, there is a function dedicated to retrieving a team based on its name (the get() method also returns a promise): public getTeamChannelByName(teamId: string, cha ...

Retrieve a list of all file names within a designated directory using Angular

I am working on my Angular app and I need to list all the file names inside the assets folder. To achieve this, I am planning to utilize the npm library called list-files-in-dir https://www.npmjs.com/package/list-files-in-dir Here is the service impleme ...

Is it possible to use AngularJS promise scheduling with `async`/`await` syntax?

When working with AngularJS services, TypeScript often recommends that I switch my code to use async/await functions. https://i.sstatic.net/vks1i.png While I understand that using the await keyword is compatible with third-party promises because it essen ...

Modify the empty message for the PrimeNG multiselect component

Is there a way to customize the message 'no results found' in p-multiselect on Angular? I have successfully changed the default label, but I am struggling to find a solution to override the empty message. Here is my code snippet: <p-multiSel ...

Bringing in External Components/Functions using Webpack Module Federation

Currently, we are experimenting with the react webpack module federation for a proof of concept project. However, we have encountered an error when utilizing tsx files instead of js files as shown in the examples provided by the module federation team. We ...

Angular application's HTML Canvas unexpectedly changes to a black color when I begin drawing

Currently, I am developing an Angular application in which users can draw text fields on PDF pages. To achieve this functionality, I have integrated the ng2-pdf-viewer library and created a PDF page component that incorporates an HTML canvas element. Howe ...

Having trouble getting access to FormArray content for validation due to receiving null or undefined errors

CSS Tricks <form [formGroup]="newMovieForm"> <ng-container formArrayName="actors"> <ng-container *ngFor="let actor of (actors['controls'] || []) ; let i = index"> <div [formGroupN ...

Unconventional way of assigning class properties in Typescript (Javascript): '?='

Recently, I came across the ?= assignment expression within a class property declaration. Can anyone provide some insight into what this means? I am familiar with the new Optional Chaining feature (object?.prop), but this particular syntax is unfamiliar t ...

Error in Angular 8: The type of '[object Object]' is an object, whereas NgFor only supports binding to Iterables such as Arrays

I recently started using Angular 8 and I'm dealing with an issue while trying to fetch data from an http get request. I am attempting to iterate through the data using *ngFor but unfortunately encountering this error. Any suggestions on how to resolv ...