The JavaScript function is returning an undefined array

I have a function named loadTileSet() that is supposed to return an array called arrTiles containing image data. However, the function is returning UNDEFINED. I am using push method to populate the array..

function loadTileSet(){
        var canvas = document.getElementById('fakeCanvas');
        $('#fakeCanvas').hide();
        var ctx = $("canvas")[0].getContext('2d');
        var imgTileSet = new Image();
        imgTileSet.src = 'tileset.png';
        var imageTileNumWidth = 23;
        var imageTileNumHeight = 21;

        var arrTiles = [];

        imgTileSet.onload = function(){

            var imageWidth = imgTileSet.width;
            var imageHeight = imgTileSet.height;
            sndCanvasWidth = imageWidth/imageTileNumWidth;
            sndCanvasHeight = imageHeight/imageTileNumHeight;
            canvas.width = imageWidth;
            canvas.height = imageHeight;
            ctx.drawImage(imgTileSet,0,0,imageWidth,imageHeight);

            var i=0;
            var j=0;
            var t=0;
            for(i=0;i<imageWidth;i+=sndCanvasWidth){
                for(j=0;j<imageHeight;j+=sndCanvasHeight){
                    var myImageData = ctx.getImageData(j,i,sndCanvasWidth,sndCanvasHeight); 
                    arrTiles.push(myImageData);  
                }
            }
            return arrTiles;
        }
    }

Now I'm attempting to assign this array to another variable

var newArray = loadTileSet();
console.log(newArray[0]);

Answer №1

The issue has been highlighted by Bergi in the above comment. This process operates asynchronously, so it needs to be managed accordingly. Essentially, a callback approach should be implemented:

function fetchTileSet(callback) {
    // ...

    imgTileSet.onload = function () {
        // Instead of returning, execute the callback
        callback(tileArray);
    };
}

fetchTileSet(function (newArr) {
    // Perform operations with newArr here
});

Answer №2

There is an issue with your function not delivering a return value. Additionally, the array population logic seems to be confined within the .onload function.

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 switch statement within a non-void function may encounter a potential end of control

I am trying to create a simple calculator. I am struggling with the warning message "Control may reach end of non-void function." for the f() function. Can anyone offer suggestions? Below is my code snippet: #include <iostream> using namespace std ...

How can the parameters -i -u "clientId:" be interpreted when translating a curl command into Ajax?

As I work on integrating a 3rd party API into my website, I am currently in the testing phase using Postman (the Chrome Extension) before proceeding to write my AngularJS Service with $http. However, there is one aspect of the process that has me puzzled. ...

How can you capture a redirect following a window.open in Puppeteer?

Imagine a scenario where there exists a website featuring the following code: <script type="text/javascript"> const onClick = async (event) => { var page = window.open('', '_blank'); var url = await someCryp ...

Canvas cannot be duplicated due to tainting, html2canvas

I have encountered an issue with my Snapshot button in HTML. Despite trying to add crossorigin="anonymous" to my script, I am still facing the problem of a Tainted Canvas when clicking the button. The button function is as follows: $('#snap').cli ...

Is there type promotion when passing an address to a pointer?

When setting up the pointer p in this code snippet: int a[10], *p; p = &a[0]; I find myself questioning whether the type of &a[0] is pointer to int or simply an int? This uncertainty arose after reading the following statement: By using a ...

Tips on preventing the opening of a new browser tab by using Ctrl + click

Hey there, I've got a list of products that can be selected using the Ctrl key. $(parentSelector).on("click", function (evnt) { evnt.stopImmediatePropagation(); var item = $(evnt.delegateTarget) ...

How can we eliminate every item of a specific type from an array?

On my Angular controller, I've set up a method linked to a click handler in the scope. This function checks if a checkbox is checked or unchecked and toggles the associated objects in an array accordingly. The code block where I push objects back int ...

Void animations in Angular 2 fail to trigger upon removal

How can I trigger animations when removing a DOM element in Angular2? import { Component, Input, Output, EventEmitter } from '@angular/core'; import { FormGroup, FormControl, Validators } from "@angular/forms"; import { trigger, state, st ...

Node.js Error: RegEx Pattern Does Not Match

Here is a regex pattern to consider: ^[^-\s][a-zA-Z\sàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ\d!@#$\+%&\'*]{1,20}$ I tested this regex on w ...

accessing elements of an octave matrix with a different array

Hey there, I'm working with a three-dimensional octave array called A that has the size [x y z]. Additionally, I have another array B with dimensions n * 3. Let's say B(0) gives me [3 3 1]. I want to access that specific location in array A, m ...

Could someone kindly provide a detailed explanation of this Javascript code, breaking it down step

I'm currently learning Javascript and stumbled upon this code snippet. However, I'm having trouble grasping its functionality. Can someone please break it down for me step by step? var ar1 = [1, 5, 6, 4, 3, 5, 100, -20]; function funDo(ar) { ...

Can a synchronous loop be executed using Promises in any way?

I have a basic loop with a function that returns a Promise. Here's what it looks like: for (let i = 0; i < categories.length; i++) { parseCategory(categories[i]).then(function() { // now move on to the next category }) } Is there ...

Step-by-step guide to creating a dynamic button that not only changes its value but also

I am trying to implement a translation button on my website that changes its value along with the text. Currently, I have some code in place where the button toggles between divs, but I am struggling to make the button value switch as well. Given my limit ...

Creating a URL using axios in Vue based on router parameters

I'm struggling to construct a string that I can use with axios to fetch specific data from an API. Unfortunately, I can't seem to figure out how to use computed or mounted in this situation. The current code keeps giving me an error saying that r ...

What could be causing variations in the performance of my Speech Recognition code each time I run it?

Check out my code snippet: export class voiceRecognition { constructor() { } public startVoiceRecognition() { const recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimresults = false; recogn ...

Can Hapi-Joi validate a payload consisting of either an Array of objects or a plain Javascript object?

How can I create a schema to validate payloads for a post call that accepts either a single JS object or an array of objects to be saved in the database? JS object { label: 'label', key: 'key', help_text: 'text' } ...

Establish the starting time for the timer and use the setInterval() function according to the seconds stored within the object

How can I configure the values of timerOn, timerTime, and timerStart to make the watch start counting from 120 seconds? Currently, the clock starts counting from 3 minutes and 22 seconds, but it should start from 2 minutes. You can find all the code here: ...

Toggle Vue transitions on and off with a boolean parameter

Is there a way to dynamically disable a transition animation in Vue based on a boolean value? Currently, the animation is enabled with the following code: <transition name="fadeUp"> <div v-if="elIsVisible"> <p>Foo Bar</p> ...

Discovering if an array includes a particular value in JavaScript/jQuery

Is there a way to check if the list with the class .sidebar contains an item with data-id="1"? <ul class="sidebar"> <li data-id="1">Option 1</li> <li data-id="2"> Option 2</li> <li data-id="3"> Option 3</li&g ...

The content of array element 0 remains unchanged

I am currently working with an array and trying to delete its content by setting null in the array[0], but it is not working as expected. For example, if I enter "Jesper," when I print nameBuffer[1], it returns 'e'. As a temporary workaround, I ...