Practical tips for utilizing drawImage once all images in an array have been fully loaded

I am having trouble rendering images using the drawImage function after they are loaded. I attempted to solve the issue by using setTimeout, but it does not work consistently.

Below is my code:

    while(FocusItem.length>0)
    {
        FocusItem.pop();
    }

    ftx=canvas.getContext('2d');

    focusImageBackground = new Image();
    focusImageBackground.src = "./images/odaklanma/odaklanmaBackground.jpg";

    if(RandomSoru==15)
        finishSoru=true;

    if(finishSoru)
    {
        RandomSoru = Math.floor((Math.random() * 15)+1);
        tempRandomSoru=RandomSoru;
    }

    if(RandomSoru==tempRandomSoru)
    {
        RandomSoru = Math.floor((Math.random() * 15)+1);
    }

    var soru = new Object();
    soru["image"] =  new Image();
    soru.image.src = './images/odaklanma/level/'+RandomSoru+'/soru.png';
    soru["x"] = 341;
    soru["y"] = 140;
    FocusItem.push(soru);

    var dogru = new Object();
    dogru["image"] =  new Image();
    dogru.image.src = './images/odaklanma/level/'+RandomSoru+'/dogru.png';
    dogru["x"] = xDogru;
    dogru["y"] = 280;
    FocusItem.push(dogru);

    var yanlis = new Object();
    yanlis["image"] =  new Image();
    yanlis.image.src = './images/odaklanma/level/'+RandomSoru+'/yanlis.png';
    yanlis["x"] = xYanlis1;
    yanlis["y"] = 280;
    FocusItem.push(yanlis);

    var yanlis2 = new Object();
    yanlis2["image"] =  new Image();
    yanlis2.image.src = './images/odaklanma/level/'+RandomSoru+'/yanlis1.png';
    yanlis2["x"] = xYanlis2;
    yanlis2["y"] = 280;
    FocusItem.push(yanlis2);

}

if(focusImageBackground.complete){
    if(FocusItem[0].image.complete && FocusItem[1].image.complete && FocusItem[2].image.complete && FocusItem[3].image.complete)
    drawFocus();
    else
        setTimeout(drawFocus,600);
}
else
    focusImageBackground.onload=function(){
        if(FocusItem[0].image.complete && FocusItem[1].image.complete && FocusItem[2].image.complete && FocusItem[3].image.complete)
            drawFocus();
        else
            setTimeout(drawFocus,600);
    }


function drawFocus(){
ftx.drawImage(focusImageBackground,0,0);

for (var i=0; i<FocusItem.length; i++){
    FocusItem[i].image.onload=function(){
        ftx.drawImage (FocusItem[i].image, FocusItem[i].x, FocusItem[i].y);
    }

}

}

Answer №1

If you preload all your images before executing the rest of your code, you can ensure they are all loaded. The following simplified method demonstrates how to load an array of image URLs and track their loading progress.

Here is a concise example (excluding extraneous code) that showcases how to efficiently handle image loading using a callback function:

function loadImagesSequentially(srcs, callback) {
   var images = [], img;
   var remainingCount = srcs.length;
   
   for (var i = 0; i < srcs.length; i++) {
       img = new Image();
       images.push(img);
       
       img.onload = function() {
           --remainingCount;
           
           if (remainingCount === 0) {
               callback(srcs);
           }
       };
       
       img.src = srcs[i]; // Ensure setting .src after defining onload handler
   }
   
   return images;
}

// Sample array of image filenames
var fileNames = ["image1.png", "image2.png", "image3.png"];

// Generate full URLs array
var urls = [];
for (var j = 0; j < fileNames; j++) {
    urls.push('./images/directory/' + fileNames[j]);
}

// Load all images and trigger callback when all are loaded
var loadedImages = loadImagesSequentially(urls, function() {
    // Handle loaded images here e.g., rendering them on screen
});

This code snippet was inspired by my previous response available at: Cross-browser solution for a callback when loading multiple images?

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

Encountering a problem with scrolling the modal to the top

I am currently working on a code snippet that involves scrolling the modal to the top position. The purpose of this is to display form validation messages within the modal popup. Below are the jQuery code snippets that I have attempted: //Click event t ...

Receiving an abundance of alert notifications triggered by the search functionality of jsTree

I've created a function to search for text within the jsTree framework. The goal is to highlight the node if the search text is found. If not, inform the user with a message saying "No node matching the search string, please try again." However, I&a ...

Plugin for managing responses other than 200, 301, or 302 in forms

Currently, I am using the jQuery Form Plugin in my project. Everything works smoothly when the server sends a 200 response as it triggers the success listener seamlessly. However, according to the standard protocol, the browser automatically handles 301 ...

Automatically populate select boxes with values from a different source using PHP

I'm in the process of setting up automatic population for 2 select boxes on a website. When a user chooses a class, the second select box automatically displays the main specialization of that class. If the user selects Tank (for example), the third ...

Tips for setting a default value for the local file in React Native

I am attempting to assign a default value to my Avatar component in React Native Elements as I do not have all the required icon files prepared. However, when I use the OR logic, it does not seem to work as expected. What is the correct approach to achie ...

What is the best way to calculate the total number of results using ajax?

Encountering an issue with the total count of ajax search results. Getting an error message "Method Illuminate\Database\Eloquent\Collection::total does not exist." when using directives, for example: <div class="searched-item"&g ...

Changing the text of a link when hovering - with a transition

Seeking a straightforward way to change text on a link upon :Hover. I desire a gentle transition (text emerges from below) and fallback to default if JavaScript is disabled. HTML <div class="bot-text"> <a href="">Visit this site</a> ...

Server experiencing slow performance with Node.js formidable file uploads

When sending files as form data along with some fields using an http post request in angular.js and receiving file in app.post in node.js, the performance is inconsistent. While local testing shows a fast upload speed of 500 mb/sec with formidable, on the ...

What to do when your Numpy array exceeds RAM capacity: Store to disk or use an out-of-core approach?

In my workflow, I have a process where I add data to an initial pandas Series object. This empty array could also be a NumPy array, or a simple list. in_memory_array = pd.Series([]) for df in list_of_pandas_dataframes: new = df.apply(lambda row: comp ...

Utilizing Vue 2 and Axios to toggle visibility of a div based on the response of an Axios request

I have a div on my website <div class="ui-alert" v-show="isCaptchaError"> ... </div> The variable isCaptchaError is initialized in my Vue instance: const form = new Vue({ el: '#main-form', data: { ...

Using PHP within Drupal, how can I show or hide a link as needed in PHP and Drupal?

Let me simplify my question - In the code snippet provided, how can I display the "Change" link only when the status value is "A"? I am currently struggling with the combination of Drupal module structure and PHP as I am still in the learning phase of mod ...

Setting a variable for a JavaScript function to insert a video - a step-by-step guide

Here is a grid structure that I am working with: <div class="main"> <ul id="og-grid" class="og-grid"> <li> <a href="http://..." data-video="my-url" data-largesrc="images/1.jpg" data-title="Title" data-descript ...

Understanding the concept of "this" within a callback situation

Given class functions game.PlayScreen = me.ScreenObject.extend({ onResetEvent: function() { this.setAll(); //calls setAll(), which calls setGlobals() this.saveNextLevelData(this.setAll); }, saveNextLevelData : function (cal ...

Tracking a razor ajax form using pace.js has never been easier with these simple steps

I'm currently exploring the use of pace.js with my Razor ajax form. The form generates a Partial View upon submission. Pace.js, as per its documentation, automatically monitors all ajax requests lasting longer than 500ms without any additional configu ...

Instructions for sending an email through a form while displaying a pop-up message

My Objective To create a functionality on my website where users can input their email addresses in a form and receive a validation popup indicating whether the email is valid or not. Background Information I am currently working on a website that allow ...

Unable to verify POST $http request using $httpBackend

Currently, I am in the process of writing unit tests to cover the http requests of my app. Using Jasmine and Karma, I have been following a tutorial on how to use $httpBackend from https://docs.angularjs.org/api/ngMock/service/. However, I encountered an e ...

Stylesheets from node_modules cannot be imported without using the tilde (~) character

Struggling to develop a basic web app using material-components-vue alongside vue-cli and webpack, I encountered an issue with importing stylesheets from node_modules without prefixing them with ~. After experimenting with various webpack/vue-cli configur ...

Restrict input to only text characters in a textbox using AngularJS

Looking for a way to ensure that users can only input characters into a textbox in my project. Any suggestions on how I can accomplish this? ...

Handy Node.js package for building a JSON API in a Ruby on Rails application

In the process of creating my Titanium Mobile app, I encountered a connection with a Rails JSON API. I found myself needing to create model objects for Rails model objects, which became quite tedious due to pagination and other factors. I am on the looko ...

Guide on Executing a Callback Function Once an Asynchronous For Loop Completes

Is there a way to trigger a callback function in the scan function after the for await loop completes? let personObj = {}; let personArray = []; async function scan() { for await (const person of mapper.scan({valueConstructor: Person})) { ...