The function get() in p5.js will provide you with an array of pixels that is empty

I am currently working on a project that is inspired by this particular video. Within p5.js, I have been utilizing the get() function. My goal is to divide a large tileset into smaller images and store them in an array. However, I have encountered an issue where the get() function is returning an empty pixels array. Here is a snippet of my code:

tilesImages = [];  // tiles array
function preload() {
    let tilesImage = loadImage(TILEMAP_PATH + "tiles.png", () => {
        console.log("Tiles loaded successfully");  // This message is logged
    }, () => {
        console.log("An error occurred when loading tiles");
    });
    for (let i = 0; i < TILE_HORIZONTAL; i++) {
        for (let j = 0; j < TILE_VERTICAL; j++) {
            let x = i * TILE_SIZE + TILES_SPACE;
            let y = j * TILE_SIZE + TILES_SPACE;
            if (i == 0) {
                x = 0;
            }
            if (j == 0) {
                y = 0;
            }
            var img = tilesImage.get(x, y, TILE_SIZE, TILE_SIZE);  
            tilesImages.push(img);
        }
    }
}
function setup() {
    console.log(tilesImages[0].pixels);  
}

In attempting to resolve this issue, I consulted this source, but it only resulted in drawing vertical pink lines on my small image.

The tileset I am using can be found at: (located on the right)

While I am currently resorting to single images, I am eager to discover a solution to this problem. Thank you.

Answer №1

The current issue at hand seems to be the lack of waiting for the image to fully load. The loadImage function operates in an asynchronous manner. Essentially, it initiates the loading process but does not wait for its completion before moving on. Consequently, any subsequent code will run while the loading is still ongoing. Utilizing a callback function can help execute code post-loading. Below is an updated version of your script that addresses this concern:

tilesImages = []; // array for tiles
function preload() {
  let tilesImage = loadImage(
    TILEMAP_PATH + "tiles.png",
    () => {
      console.log("Tiles loaded successfully"); // Logged message
      // Execution halted until all tiles are loaded to use tilesImage.get()
      for (let i = 0; i < TILE_HORIZONTAL; i++) {
        for (let j = 0; j < TILE_VERTICAL; j++) {
          let x = i * TILE_SIZE + TILES_SPACE;
          let y = j * TILE_SIZE + TILES_SPACE;
          if (i == 0) {
            x = 0;
          }
          if (j == 0) {
            y = 0;
          }
          var img = tilesImage.get(x, y, TILE_SIZE, TILE_SIZE); // Extract tiles from tileset
          tilesImages.push(img);
        }
      }
    },
    () => {
      console.log("An error occurred during tile loading");
    }
  );
}

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

Failure to trigger a follow-up function in webSQL transaction's success callback

Review the code below. I have called setQuestion() within the successCallBack of db.transaction but am encountering an error: Uncaught TypeError: this.setQuestions is not a function. Can you spot any issues in my code? game.module( "game.scenes.scene" ) ...

Showing both SubTotal and Total simultaneously in a JavaScript powered interface

Recently diving into Javasript, I came across the code snippet below from a different source that I tweaked to suit my needs. My goal is to show the subtotal in the third column for each benefit while displaying the total of the entire form. However, I&apo ...

Using Node.js, iterate over every key-value pair within a Redis hash data structure

I am currently navigating my way through the world of redis and node, attempting to iterate over some test hash keys that I have generated. My goal is to display the results on the screen. The expected output should look like this: { "aaData": [['Tim ...

Detecting errors on the client side with JSON payload in Next.js and a personalized server

Working with Next.js and a custom Express server, I've encountered an issue regarding basic API error handling. I have set up a simple error handling middleware that looks like this: app.use((err, req, res) => { res.status(400).send(message); ...

``Why is my setFeatureState function not updating the value in my Mapbox map

I've been attempting to change the stroke of a circle upon clicking it on mapbox. Despite following mapbox's documentation, the values don't seem to update. The console is also clear. t.map.addLayer({ id: id, type: 'circle&apo ...

Footer positioned correctly with relative DIV

I find myself in a state of complete confusion. Coding is not exactly my forte, so I suspect I have made a significant error somewhere that is causing the following issue: My goal is to create a sticky footer. The footer does indeed stick to the bottom of ...

React JSX is failing to return either an Icon or String value depending on the input provided by the user for the password

I'm currently developing a registration page where I want to display a message saying "Your password must be at least 12 characters long" or show a green checkmark when the user types a password that meets this requirement. However, nothing is being d ...

obtaining pictures from information obtained in vuejs

Trying to showcase images in my code that are already stored in my data like this: <div > <tr v-for='(ships,index) in destroyedShipBox' :key='index'> <td>{{ships}}</td> ...

When deployed, Webpack 2.2.0.rc-0 will condense and optimize vendor.js and manifest.js, but will not perform the same action on bundle

I have been troubleshooting why my vendor and manifest files are minified and uglified, but my bundle is not. I am wondering if it could be related to the order of the plugins or perhaps something to do with the CommonsChunkPlugin? Here is the code for my ...

The command 'create-react-app' is not valid and cannot be recognized as an internal or external command, operable program, or batch file

I've been struggling to set up a React project, as the create-react-app my-app command doesn't seem to be working. Can anyone offer some assistance? Here are the commands I'm using: npm install -g create-react-app create-react-app my-app ...

Identify Unintended Javascript Modifications in Ajax Request

We have developed a unique Javascript file for our clients to utilize. This innovative snippet captures a screenshot of the website it is executed on and then securely transmits it back to our server using jQuery.post() Given the sensitive nature of our i ...

Expressjs Error- ReferenceError: cors has not been defined in this context

While working on creating a backend using ExpressJs, I encountered an error when running the backend. app.use(cors()) ^ ReferenceError: cors is not defined at Object.<anonymous> (C:\Users\hp\Desktop\Entri\kanba\ ...

What is the best way to link data from SQL Server to an HTML webpage?

Seeking assistance on how to display data from a SQL Server database in an HTML page using JavaScript, AJAX, and jQuery without the need for C#, PHP, VB.NET etc. Can someone please provide some reference links or share example code? ...

Adjust text at multiple positions using Javascript

I am working on parsing a complex query and developing a tool using the following sample: var str =" SELECT 'Capital Return' AS Portfolio_Classification , '(Gross)' AS Portfolio_Type , '0.21%& ...

"An error was encountered with the JSON acceptance due to an

When I call an external json API, the response is coming back as JSON. If I don't specify the datatype as JSONP, the API fails due to an access control issue. I can successfully hit the API with Postman and receive the response. However, in the conso ...

The ajax keypress event is malfunctioning and the ActionResult parameter is failing to capture any data

I am facing an issue where I want to update the value of a textbox using AJAX on keypress event, but the controller is not receiving any value to perform the calculation (it's receiving null). <script> $('#TotDiscnt').keypress(fu ...

Sending both the minimum and maximum slider values to PHP using POST can be achieved by formatting the data correctly

I am attempting to transmit the minimum and maximum values to PHP using submit through a dual slider bar The static page makes a request to the server-side PHP code <?php include('server/server.php') ?> Below is the JavaScript code ...

What is the best way to retrieve data from multi-dimensional JSON structures?

Looking to extract specific values from my JSON file. console.log( objects.assignments.header.report_type ); I need to display HOMEWORK Javascript $.ajax({ url: "/BIM/rest/report/assignment", type: "POST", dataTyp ...

Accessing Form Data as an Array in a Single Page Application

I'm currently in the process of developing a single-page PHP application and I'm experimenting with submitting the form using ajax .post() instead of the traditional form submission that redirects to another page. However, I'm experiencing d ...

Encountering XMLHttpRequest errors when trying to make an AJAX POST request

I'm encountering an issue with a modal containing a form for submitting emails. Despite setting up the ajax post as usual, the submission is failing consistently. The console displays the following two errors: Setting XMLHttpRequest.withCredent ...