What is the method for presenting preloaded image slices stored in a two-dimensional array rather than using placeholders?

I am facing an issue while trying to put together and showcase image slices that have already been loaded into a two-dimensional array. Instead of displaying the images, all I see are empty placeholders.

The image slices were preloaded using a JavaScript function, but when I attempt to retrieve and compile them with another JavaScript function, the result is just placeholders instead of actual images. The initial JavaScript function for preloading the image slices is invoked at the end of the HTML page's head section and utilizes a query string to fetch a portion of the image file name (queryData[2]). On the other hand, the second JavaScript function responsible for assembling the images is included in the body tag and called upon as onload=assembleImage();. Throughout both functions, I've incorporated console.log statements which confirm that the image slices are indeed present. However, why am I unable to view the actual images and only seeing placeholders? Below is the code snippet:

// First function to preload image slices into a two dimensional array.


function preloadImages(){

    preloadImages = [];
    var row = 5;
    var col = 5;

    for (var r = 0; r < row; r++){
        preloadImages[r] = new Image();
        for (var c = 0; c < col; c++){
            preloadImages[r][c] = new Image();
            preloadImages[r][c].src = queryData[2] + "_" + (r) + "_" + (c) + ".jpg";    
        }
    }
    //console.log(preloadImages[r][c]);
}

// Second function to retrieve and assemble image slices.

function assembleImage(){   

    var row = 5;
    var col = 5;
    var assembleImage = document.getElementById("prodImage");
    var imageTable = "<table>";

    for (var r = 0; r < row; r++){
        imageTable += "<tr>";
            for (var c = 0; c < col; c++){
                imageTable += "<td>";
                imageTable += "<img src = " + preloadImages[r][c].src + "/>";
                imageTable += "</td>";

            console.log(preloadImages[r][c])
            }
        imageTable += "</tr>";
    }
    imageTable += "</table>";
    assembleImage.innerHTML = imageTable;
}

Answer №1

It seems like one of the main obstacles you're facing is related to how you are assigning preloadImages[r] to a new Image rather than an Array. Furthermore, there is a mix-up in defining preloadImages as both a function and a variable (implicitly set as global) for your two-dimensional Array. By making some adjustments to these variables and cleaning up the code a bit, everything works smoothly, as demonstrated below:

document.addEventListener('DOMContentLoaded', function () {

    var queryData = [
        'https://makelin.us/100/100',
        'https://makelin.us/100/100',
        'https://makelin.us/100/100'
    ];
    var preloadImages = [];
    // A function to preload image slices into a two-dimensional array.
    function preloadAllImages() {
        var row = 5;
        var col = 5;

        for (var r = 0; r < row; r++) {
            preloadImages[r] = [];
            for (var c = 0; c < col; c++) {
                preloadImages[r][c] = new Image();
                preloadImages[r][c].src = queryData[2];
            }
        }
        // console.log(preloadImages);
    }
    preloadAllImages();

    // Another function to retrieve and assemble image slices.
    function assembleImage() {
        var row = 5;
        var col = 5;
        var assembleImage = document.getElementById("prodImage");
        var imageTable = "<table>";

        for (var r = 0; r < row; r++) {
            imageTable += "<tr>";
            for (var c = 0; c < col; c++) {
                imageTable += "<td>";
                imageTable += "<img src=" + preloadImages[r][c].src + "/>";
                imageTable += "</td>";

                // console.log(preloadImages[r][c])
            }
            imageTable += "</tr>";
        }
        imageTable += "</table>";
        // console.log(imageTable);
        assembleImage.innerHTML = imageTable;
        // console.log(assembleImage);
    }
    assembleImage();
});
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
<div id="prodImage"></div>
<script src="script.js">
</script>
</body>

</html>

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

Can someone assist me in understanding the proper syntax for the Node.js function that inserts a document into Watson's Discovery service from the watson-developer-cloud library?

I'm attempting to upload JSON documents into a Discovery collection using the Node.js watson-developer-cloud JDK. Here is the relevant code snippet: const DiscoveryV1 = require('watson-developer-cloud/discovery/v1'); const discovery = new D ...

Incorporating GitHub Pages content without the need for an iframe

I have a VueJS application that includes links to documentation pages. It would be great to display the documentation content within my page without users having to navigate away. Some of these docs are hosted on GitHub pages and while I could use iframes ...

search engine optimized for easy input via keyboard

I have successfully incorporated AJAX search functionality into my project, inspired by this example here. The unique feature of this implementation is the ability to navigate through search results using the TAB key. The structure of my search results tab ...

Display a success message in a div when the form is submitted

I am facing an issue with the submission of multiple forms on a page using AJAX. The problem is that when I submit a particular form, it displays success messages in all the divs instead of showing it only in the relevant div. I want each form to trigger ...

Transform your scene into a stunning 3D texture using THREE.js's 3D Render Targets feature

After exploring the THREE.js example available here, I am curious about how to avoid scenes rendered as textures from appearing 'flattened'. Essentially, I want to maintain the depth illusion within the scene when using a WebGLRenderTarget. I ha ...

Error in 'Unity3D': Array Index Out Of Bounds Exception occurred while attempting to modify sprite upon collision

Hey there, fellow Developers! I know this question has been asked before, but none of the answers provided a solution to my specific problem. Just to give you some context, I am new to unity and currently working on creating a brick breaker game. The issue ...

Picking an element that has a dynamic data attribute, but also considering those with a hyphen

Currently, I am developing a function that will select a span element when clicked based on its data attribute and value. Here is the code snippet: function moveFilterElements(event) { if ($(event).hasClass('active')) { var dataAtt ...

Vue 3 throws an error stating: "An uncaught DOMException occurred because the string contains an invalid character."

Exploring the capabilities of vue.js on a basic website. The setup consists of a single index.html file and all JavaScript is housed in an index.js file. The website is a work in progress, but there are no blockers preventing the JavaScript functionality ...

Curved Edges Ensure Non-Interactive Elements

element, there is a query about utilizing a color wheel from a repository on GitHub. The goal is to disable any actions when clicking outside of the canvas border radius in this color wheel. Various steps need to be taken to prevent unwanted outcomes: - S ...

Issue with JQuery Ajax call within If condition

My Ajax call is working perfectly in one scenario, but not in another when placed inside an if statement. I'm relatively new to JS and Ajax, so I may be missing something fundamental. Any insights would be appreciated. Thank you. The function that wo ...

Exploring grouped data objects in Vue for iteration

My data is sourced from an API and looks like this: { "ALBUMS":[ { "ID":"1", "TITLE":"'THE BEST OF" }, { "ID":"2", "TIT ...

Is the sudden disconnection from Chrome after a WebSocket handshake related to a domain mismatch or is it possibly a bug in Chrome?

I created my own WebSocket server using Python, but I encountered an issue where Chrome 4.0.249.78 dev (36714) always disconnects after the handshake process. Wanting to rule out any issues with my code, I tested it using the WebSocket server from , only t ...

Tips for creating a reusable function in React.js?

I have a script that executes on input focus and passes certain values based on a specific logic. I would like to reuse this script for multiple input fields that trigger the focus event. How can I accomplish this? This is my current script: <input ...

Showing information in a table on a webpage using JavaScript and HTML

After running a console log, I am presented with the following data: 0: {smname: "thor", sim: "9976680249", pondo: "10"} 1: {smname: "asd", sim: "9999999999", pondo: "0"} 2: {smname: "asd", sim: "4444444444", pondo: "0"} 3: {smname: "bcvb", sim: "78678967 ...

How can you tap into local storage in CSS while utilizing a chrome extension?

Can I access local storage from a Chrome extension's options file using CSS? Is it possible to use JavaScript to define a variable that can be utilized in CSS, or is local storage only accessible through JavaScript? If local storage is restricted to J ...

Retrieve your username data using Ajax

I'm working on a JSP page with the following structure: https://i.sstatic.net/3aFoz.png In updating the table in my database, I've added a new username column that accepts any string of text. Once the 'update user' button is clicked, ...

Can you explain the functionality of the following Express router?

In the tutorial I am currently following, there are 2 router methods used to retrieve articles from the database. router.param('article', function(req, res, next, slug) { Article.findOne({ slug: slug}) .populate('author') .th ...

Accessing data in form rules with Vuetify: tips and tricks

Is it possible to access a data element within a rule? Click here to see my code in action I'm attempting to change the value of a data element on a text field rule within a Vuetify form. While the rule itself is functioning properly, I'm enco ...

Using AngularJS to inject a variable into the standard filter

Currently, I am attempting to develop a custom filter that mimics the functionality of the standard Angular filter in HTML, with the distinction that it accepts a variable as input rather than a fixed value. For instance, within my html document, you may ...

Revitalize PHP through jQuery and refresh the image with a reload

I am currently working on a PHP page located at /var/www/oggi1ora.php. My goal is to run the page /usr/local/bin/oggi1ora.php every 5 seconds to generate a chart. Although the PHP script is executing correctly every 5 seconds, the image on the page is no ...