What should I do if one of my images fails to load after the previous one has loaded successfully?

My code is designed to create an animation using 3 canvases: one for the base image, one for the streamline wind map drawing, and another for an image covering part of the drawing. The following code displays the uploading of two images.

            var img = document.createElement("img");
            var cvrimg = document.createElement("cvrimg");
            img.src = "https://cors-anywhere.herokuapp.com/www.example.com/img.png";
            cvrimg.scr = "https://cors-anywhere.herokuapp.com/www.example.com/img-two.png";
            img.crossOrigin = "anonymous";
            cvrimg.crossOrigin = "anonymous";
            img.onload = function () {
                imgctx.drawImage(img, 10, 10);
                cvrimg.onload = function () {
                    console.log("maybe");
                    cvrctx.drawImage(cvrimg,10,10);
                    startDrawing(wdDataArr,wsDataArr,dataManArr,pastDataArr,onlineArr);
                }
            }

After adding some log statements to my code, I noticed that the cvrimg.onload function was not being called, and only one image was being queried in the network tab of the Chrome inspect tool.

Any tips or advice would be greatly appreciated by this aspiring programmer.

Thank you.

Answer №1

When img.onload is called, the function for cvrimg.onload is defined. However, if cvrimg loads before img.onload, the function will not be called because it is not yet defined.

Furthermore, creating an element with

cvrimg = document.createElement("cvrimg")
results in a nonsensical <cvrimg> element being created.

Option 1 – loading images in parallel

let img = document.createElement("img"),
    cvrimg = document.createElement("img");

img.src = "https://cors-anywhere.herokuapp.com/www.example.com/img.png";
cvrimg.scr = "https://cors-anywhere.herokuapp.com/www.example.com/img-two.png";

img.onload = function() {
    console.log("img loaded");
    ...
}

cvrimg.onload = function() {
    console.log("cvrimg loaded");
    ...
}

Option 2 – loading images in series

let img = document.createElement("img"),
    cvrimg = document.createElement("img");

img.src = "https://cors-anywhere.herokuapp.com/www.example.com/img.png";

img.onload = function() {
    console.log("img loaded, loading cvrimg now");
    cvrimg.scr = "https://cors-anywhere.herokuapp.com/www.example.com/img-two.png";
    ...
}

cvrimg.onload = function() {
    console.log("cvrimg loaded");
    ...
}

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

Don't waste time creating multiple popups for changing content - streamline your process

Challenge I've successfully extracted information from an array and displayed it dynamically in a tooltip/popup window above each photo on the page. However, with 56 different individuals at various locations, arranging them neatly in a grid poses a ...

Exploring Javascript through Python using Selenium WebDriver

I am currently attempting to extract the advertisements from Ask.com, which are displayed within an iframe generated by a JavaScript script hosted by Google. Upon manually navigating and inspecting the source code, I can identify the specific element I&ap ...

Node.JS program unexpectedly logging MySQL results to console and exhibiting erratic behavior

Recently, I encountered a peculiar error while working with Node.JS MySQL. Strangely, I noticed that a result was being logged in the console without any corresponding code line instructing it to do so. Even more baffling was the fact that when I intention ...

How can I download a PDF file in React.js using TypeScript on Next.js?

I've created a component to download a PDF file. The PDF file is named resumeroshan.pdf and it's located inside the Assets folder. "use client"; import resume from "/../../Assets/resumeroshan.pdf"; export default function Abo ...

JavaScript code to find a date within a specified range

I have developed a script that calculates the number of weeks between two specified dates. It then generates a table where the number of rows equals the number of weeks. The script can be viewed on JSFIDDLE Script: $('#test').click(function ...

An API built with Mongoose, Express, and Node.js is currently only able to send a single image

I have a buffer array that needs to be converted into images and sent to the user. The issue is that the current code only sends one image: const express = require("express"); const asyncHandler = require("express-async-handler"); const ...

Knockout Observable Array causing UI to freeze and not refresh properly

I recently started using knockout and am exploring the use of observable arrays to track changes from the UI. The initial data is loaded into the array and I'm attempting to dynamically add new objects to the array from another screen. Although I hav ...

Whenever I try to include something within the `componentWillUnmount` function,

I'm currently learning React on my own. I've been trying to save session data in my componentWillUnmount method. However, when I add code inside componentWillUnmount, nothing seems to happen. I tried debugging by adding console logs and debugger ...

JavaScript Asynchronous Functions Not Handling Await Calls Correctly

The two fadeInList functions control the fading animation of a continuous list split into two lines. The typeOutText function displays text and is supposed to execute List1 first, wait for it to finish, and then proceed with List2. However, after adding ke ...

Retrieve all the keys from an array of objects that contain values in the form of arrays

Looking for an efficient way to extract all keys from an array of objects whose values are arrays, without any duplicates. I want to achieve this using pure JavaScript, without relying on libraries like lodash or underscore. Any suggestions on how to impro ...

Problem with Bootstrap 3 navbar on mobile devices - not tappable or responsive

After years of using Bootstrap, I've come across a new issue with my implementation of a Bootstrap 3 Nav. While testing on a desktop browser with device emulation, the nav collapses and functions properly. However, when tapping on the header on an ac ...

Displaying images in an Android app using Volley Library along with text strings

I'm a beginner in Android development and have been able to successfully post Strings using Volley. Now I want to send Strings along with an image. I've managed to select an image from the gallery, but I am struggling with how to post it. @Overr ...

Creating a dynamic number of datasets in Chart JSWith Chart JS

After extensive searching, I thought I was on the verge of finding a solution several times, but unfortunately, no luck! I am aware that a similar question was posted yesterday: React Chartjs, how to handle a dynamic number of datasets, but it remains una ...

Utilize Javascript ES6 to Sort Through Data in a Table

I require assistance with my project using Material UI and React. There are two key implementations that I need: I am looking to create a filtering system for all rows in each column as shown in the attached image. Additionally, I need a button that can a ...

When using Asp.Net TextBox, the focus is lost after inputting the first character

I have created an Asp.Net web form (aspx) that includes a TextBox: <div id="field"> <asp:TextBox Id="Name" runat="server" MaxLength="50"/> </div> Whenever I type characters into the TextBox, I t ...

Easily adding multiple field data with the same field name into a database can be achieved using Mongoose and Node.js (specifically Express

I am new to using nodejs and exploring the creation of a project focused on generating invoices. My goal is to store product information in mongodb utilizing mongoose and express, but I'm unsure of how to proceed. Below is a snippet of my HTML code.. ...

What is the point of utilizing angular.extend in this situation?

After inheriting a codebase, I stumbled upon the following code snippet (with some parameters simplified and anonymized): /** * @param {float} num1 * @param {string} str1 * @param {string} str2 * @param {boolean} flag & @return (object) */ sr ...

What could be the reason for the Nextjs fetch request returning undefined data?

Here is the code snippet for my GET request in the API section: export default async (req, res) => { const { query: { className }, method } = req; switch (method) { case "GET": try { const classDetail = await Class.findO ...

Utilize the PHP variable HTTP_USER_AGENT to identify and analyze the user's browser

As I embark on creating a webpage, my goal is to have it display different content based on the user's browser. The SERVER [HTTP_USER_AGENT] variable initially seemed promising for this purpose, but upon inspecting the page in Chrome, I encountered: ...

Is it possible to create a replicating text box in AngularJS that multiplies when entering input

I am experimenting with creating a sequence of text boxes that dynamically generate new empty text boxes as the user enters information into each one. Each text box is required to have an ng-model value associated with it, and they should all be generated ...