How come I am unable to retrieve the x value from the bitmap? (JavaScript)

I am attempting to iterate through an array of 3 images and add them to the stage using easelJS. I also need to position them accordingly. However, when I try to access the images in the array, I encounter an error stating that I cannot set the x property of undefined. Why is it that I am unable to access the x variable of the easeljs Bitmap?

function displayPosters() {

    getPosters(); // Retrieve all images and assign them to designated array

            console.log(frontPosters);
            console.log(frontPosters.length);

    if(currentCat == Category.HOME) { // Check if the current category is HOME

        for(var i = 0; i < frontPosters.length; i++) { // Iterate through posters

            frontPosters[i].x = 40; // Set x position for testing, which is where the error occurs
            stage.addChild(frontPosters[i]); // Add poster to the stage

        }

    }

}

Below is the code responsible for loading and storing the images in the frontPosters arrray.

var frontPosters = new Array(3);

function getPosters() {

    var games = new Image(); // Create 3 images
    var apps = new Image();
    var aboutme = new Image();

    games.onload = function() { // Add image to frontImages array on load

        var gamesPost = new createjs.Bitmap(games);
        frontPosters[0] = gamesPost;

    };

    apps.onload = function() {

        var appPost = new createjs.Bitmap(apps);
        frontPosters[1] = appPost;

    };

    aboutme.onload = function() {

        var amPost = new createjs.Bitmap(aboutme);
        frontPosters[2] = amPost;

    };

    games.src = "images/assets/posters/games_poster.jpg"; 
    apps.src = "images/assets/posters/apps_poster.jpg";
    aboutme.src = "images/assets/posters/aboutme_poster.jpg";

}

Answer №1

It is considered bad practice to use for(poster in frontPosters) because you end up iterating over the Array Object instead of the values themselves (i.e. the Array). A better approach would be to use

for(var i=0; i<frontPosters.length; i++)
. In my opinion, this is the simplest solution.

for(var i = 0; i < frontPosters.length; i++) { //loop through posters
    frontPosters[i].x = 40; //set x position for testing, where the error occurs
    stage.addChild(frontPosters[i]); //add poster to stage
}

Edit

You might be experiencing a race-condition issue. This happens when you iterate over your array before all images have finished loading. When you define var frontPosters = new Array(3);, three values are automatically set to undefined and pushed into the new array.

Make sure to verify that all images have loaded before proceeding with the script.

One suggestion is to implement a callback that will only execute after the third image has finished loading.

var frontPosters = new Array(3);

function getPosters(callback) {

    var games   = new Image(),
        apps    = new Image(),
        aboutme = new Image(),
        loaded  = 0;

    games.onload = function() {
        frontPosters[0] = new createjs.Bitmap(this);
        if (++loaded === 3) callback();
    };

    apps.onload = function() {
        frontPosters[1] = new createjs.Bitmap(this);
        if (++loaded === 3) callback();
    };

    aboutme.onload = function() {
        frontPosters[2] = new createjs.Bitmap(this);
        if (++loaded === 3) callback();
    };

    games.src   = "images/assets/posters/games_poster.jpg"; 
    apps.src    = "images/assets/posters/apps_poster.jpg";
    aboutme.src = "images/assets/posters/aboutme_poster.jpg";

}

function displayPosters() {

    getPosters(function() {
        if(currentCat == Category.HOME) { 
            for(var i = 0; i < frontPosters.length; i++) { //loop through posters
                frontPosters[i].x = 40; //set x position for testing, also where error occurs
                stage.addChild(frontPosters[i]); //add poster to stage
            }
        }
    }); 

}

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

Extracting server error messages on the client side using Node.js

Before storing data in the database, my server performs validation checks. If it is unable to save the data into the database, an error message is sent. In my client-side application, how can I retrieve and display this error message? Below is the HTTP r ...

Tips for transferring data between functions in component.ts in Angular 2

When I click a button, I am passing some values using "data.someid" and I want to retrieve this value in another button click. html --- <button (click)="click1(data.someid)"></button> <button (click)="click2()"></button> In my com ...

How does the Paginate Pipe effectively retrieve the array length in an Angular 2 application?

I find myself in an interesting situation where I have a piece of code that is functioning within my Angular 2 application - it's generating the correct value, but the method behind its success is unclear to me. Specifically, I am using ng2-paginatio ...

Component updates are not working in VueJS

My Vue 1 component requires an object as a prop that needs to be filled by the user. This object has a specific structure with properties and nested inputs. The component is essentially a modal with a table containing necessary inputs. I want to perform v ...

The webpack-bundle-analyzer tool reveals that running webpack -p does not eliminate the development dependency react-dom.development.js

Here is my custom webpack configuration: const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; const SO ...

Empty placeholder image appearing at the beginning of JavaScript slideshow in Ruby on Rails

As a newcomer, I ask for your understanding if I lack knowledge in some areas. I have been working on a project and using the cycle2 plugin successfully to create a slideshow on my index page with images pulled from the internet. Now, I am trying to impl ...

Is there a glitch in JavaScript when comparing dates?

What's wrong with this code? function test() { var start = new Date(2012, 3, 31, 19, 0, 0); // Start: 3/31/2012 7:00 PM var end = new Date(2012, 4, 1, 1, 0, 0); // End: 4/01/2012 1:00 AM if (end < start) console.log("oops ...

Angular mat-select is having difficulty displaying options correctly on mobile devices or devices with narrow widths

In my Angular project, I've encountered an issue with mat-select when viewing options on mobile or low-resolution screens. While the options are still displayed, the text is mysteriously missing. I attempted to set the max width of the mat-option, but ...

Encountering an issue while attempting to locate an already existing product in the localStorage using JavaScript

I'm currently working on incorporating a cart system using localStorage and have provided the codes below. Can someone help me understand how to accomplish this? const data = { description: "Cum sociis natoque", mediaUrl: "/prod ...

Master the art of returning two functions within a single function in Javascript with NodeJS and ExpressJS

Currently, I am facing an issue where I need to combine two objects and return them in one function. The challenge lies in the fact that both objects have almost identical properties, but different values. To tackle this problem, I created two separate fu ...

Generating random triangles using Java

I am currently working on a program that is supposed to generate five random triangles, each filled with a randomly chosen color. The challenge I am facing is that the triangles are not displaying at all, instead, I just see a gray box on the screen. I h ...

Creating an npm module using an external JavaScript API script

I am currently in the process of creating an npm package using code from this repository. In my possession is the "minified" js file called http_www.webglearth.com_v2_api.js, which is automatically downloaded by IntelliJ when the <script src=""> tag ...

Getting the environment variable from Rails in your JavaScript: A guide

I am currently working on implementing a key system within my application. In the code I am using, there is logic that looks like this: $('.key-test-button').on('click', function(){ if ($('.key-test-input').val() === "MYK ...

The ng-view DIV in Angular JS 1.x mysteriously vanishes

Currently, I am working on a project that involves angularJS and ASP.NET in Visual Studio 2013. However, I have encountered a frustrating issue where my DIV node for ng-view is being replaced with an ng-view comment without any errors appearing while testi ...

Exploring the power of Vue3 with Shadow DOM in web components

I've been experimenting with web components using Vue3 and I'm curious about how the Shadow DOM works. I encountered an issue where a third party library was trying to access elements using getElementById() and it was throwing an error because th ...

Add content to div element using input from textarea

I'm attempting to create a basic text editor where users can input text and by clicking the edit button, it will add that text to the end of the id="textArea". However, nothing happens when I click the edit button after entering text in the textarea. ...

Rotating and scaling an image simultaneously using CSS3

I am feeling very puzzled. Why am I unable to simultaneously scale and rotate? Despite my attempts, it seems to be not working: .rotate-img{ -webkit-transform:scale(2,2); -webkit-transform:rotate(90deg); margin-left:20%; margin-top:10%; } ...

Is it possible to update the CSS file of an external SVG file in real-time?

Is there a way for an SVG image to reference another CSS file? A webpage contains an SVG file. A button allows users to switch between classic colors and high contrast mode on the entire webpage, including the SVG image. Attempt w.css (white backgrou ...

Trouble with constructor and array functionality, converting String to String[]

Currently, I am facing difficulty understanding why I am unable to input any interests into my constructor while attempting to run tests. The error message indicates that String cannot be converted to String[]. Any assistance in identifying where I might ...

How to iterate through properties declared in an Interface in Angular 12?

Before Angular 12, this functioned properly: export interface Content { categories: string[] concepts: Topic[] formulas: Topic[] guides: Topic[] } //this.content is of type Content ['formulas', 'concepts'].forEach(c =&g ...