Entrance Chat Gallery Guilds Search Everyone Wiki Login Register

Welcome, Guest. Please login or register. - Thinking of joining the forum??
October 03, 2025 - @982.73 (what is this?)
Activity rating: Four Stars Posts & Arts: 53/1k.beats Unread Topics | Unread Replies | My Stuff | Random Topic | Recent Posts Start New Topic  Submit Art
News: :dive: Are u having fun?? :dive: Guild Events: PowerPC Activity Week!

+  MelonLand Forum
|-+  World Wild Web
| |-+  ✁ ∙ Web Crafting
| | |-+  ☔︎ ∙ I need Help!
| | | |-+  Javascript - Wait for images on a webpage to load


« previous next »
Pages: [1] Print
Author Topic: Javascript - Wait for images on a webpage to load  (Read 190 times)
bodypoetic
Casual Poster ⚓︎
*
View Profile WWWArt


for thine is the kingdom of wire and bone
⛺︎ My Room
Itch.io: My Games
RSS: RSS

Guild Memberships:
Artifacts:
Joined 2025!
« on: September 27, 2025 @774.34 »

I have been beating my head against this one for long enough that it probably warrants asking for help! I'm having a problem with my blog page - specifically, the lines between the stars. On a first load, they're all wonky and out of alignment, like so:



Refreshing the page, or loading it when the browser has it cached, reliably fixes it. As I understand it, what's happening here is that the Javascript is generating the lines before the images have loaded, when the centre of the div is in a different location.

So what I want to accomplish is for my code to wait until the star images have loaded, and then generate the lines connecting them. I gather that what I want here is a promise - only I'm struggling to wrap my head around async functions. All my attempts at implementing them have resulted in the lines not generating at all, at which point I am typically feeling so defeated that I just go 'well, wonky lines are better than no lines', delete the offending code, and give up for the day - only to repeat the pattern a week or so later.

Am I right in thinking that there must be a simpler way to do this? I feel so sure that I am missing something obvious here - any tips would be greatly appreciated!

Code
const getOffset = (el) => {
    const rect = el.getBoundingClientRect();
    return {
        left: rect.left + window.pageXOffset,
        top: rect.top + window.pageYOffset,
        width: rect.width || el.offsetWidth,
        height: rect.height || el.offsetHeight
    };
}

connect = (div1, div2, color, thickness) => {
    const off1 = getOffset(div1);
    const off2 = getOffset(div2);

    const x1 = off1.left + (off1.width / 2);
    const y1 = off1.top + (off1.height / 2);

    const x2 = off2.left + (off2.width / 2);
    const y2 = off2.top + (off2.height / 2);

    const length = Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))) - 50;

    const cx = ((x1 + x2) / 2) - (length / 2);
    const cy = ((y1 + y2) / 2) - (thickness / 2);

    const angle = Math.atan2((y1 - y2), (x1 - x2)) * (180 / Math.PI);

    const htmlLine = "<div style='padding:0px; margin:0px; height:" + thickness + "px; background-color:" + color + "; line-height:1px; position:absolute; left:" + cx + "px; top:" + cy + "px; width:" + length + "px; -moz-transform:rotate(" + angle + "deg); -webkit-transform:rotate(" + angle + "deg); -o-transform:rotate(" + angle + "deg); -ms-transform:rotate(" + angle + "deg); transform:rotate(" + angle + "deg);' />";

    document.body.innerHTML += htmlLine;
}

connect(document.getElementById('d1'), document.getElementById('d2'), 'white', 1);
connect(document.getElementById('d2'), document.getElementById('d3'), 'white', 1);
connect(document.getElementById('d3'), document.getElementById('d4'), 'white', 1);
Logged

Quote
The prince chose to sleep on, and the princess chose to wake up. At the top of that tall tower, the princess bid farewell to the prince. No—she wasn’t the princess any longer. She quit being a “person (thing) ruled by someone”. The victory bells rang, but there was no “tower (rule)” beyond them now. She’d learned where freedom lay. [...]

The world (the stage) is free and wide.

Melooon
Hero Member ⚓︎
*****
View Profile WWWArt


So many stars!
⛺︎ My Room
SpaceHey: Friend Me!
StatusCafe: melon
iMood: Melonking
Itch.io: My Games
RSS: RSS

Guild Memberships:
Artifacts:
coolest melon on the web!Emergency feel-good teaa silly heart 4 melon :)Hyperactive DonutGreat Posts PacmanThanks for being rad!
« Reply #1 on: September 27, 2025 @797.21 »

Hello! Usually wrapping your code in the window onload event will do it (its an event that only triggers when everything in the browser window has finished loading.

Sooo in your case:
Code
window.onload = function() {
    const getOffset = (el) => {
	    const rect = el.getBoundingClientRect();
	    return {
	        left: rect.left + window.pageXOffset,
	        top: rect.top + window.pageYOffset,
	        width: rect.width || el.offsetWidth,
	        height: rect.height || el.offsetHeight
	    };
	}
	 
	connect = (div1, div2, color, thickness) => {
	    const off1 = getOffset(div1);
	    const off2 = getOffset(div2);
	 
	    const x1 = off1.left + (off1.width / 2);
	    const y1 = off1.top + (off1.height / 2);
	 
	    const x2 = off2.left + (off2.width / 2);
	    const y2 = off2.top + (off2.height / 2);
	 
	    const length = Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))) - 50;
	 
	    const cx = ((x1 + x2) / 2) - (length / 2);
	    const cy = ((y1 + y2) / 2) - (thickness / 2);
	 
	    const angle = Math.atan2((y1 - y2), (x1 - x2)) * (180 / Math.PI);
	 
	    const htmlLine = "<div style='padding:0px; margin:0px; height:" + thickness + "px; background-color:" + color + "; line-height:1px; position:absolute; left:" + cx + "px; top:" + cy + "px; width:" + length + "px; -moz-transform:rotate(" + angle + "deg); -webkit-transform:rotate(" + angle + "deg); -o-transform:rotate(" + angle + "deg); -ms-transform:rotate(" + angle + "deg); transform:rotate(" + angle + "deg);' />";
	 
	    document.body.innerHTML += htmlLine;
	}
	 
	connect(document.getElementById('d1'), document.getElementById('d2'), 'white', 1);
	connect(document.getElementById('d2'), document.getElementById('d3'), 'white', 1);
	connect(document.getElementById('d3'), document.getElementById('d4'), 'white', 1);
};
Logged


everything lost will be recovered, when you drift into the arms of the undiscovered

Artifact Swap: Berry StoneSapphirePeace MoonLurbyFrutiger Aero BallLive Slow Die Youngspring 2023!MIDI Warrior1234 Posts!Rising Star of the Web AwardMessage Buddy
MediocreMetastasis
Sr. Member ⚓︎
****
View Profile WWWArt


Personal Text
⛺︎ My Room
Itch.io: My Games

Guild Memberships:
Artifacts:
Joined 2025!
« Reply #2 on: September 28, 2025 @87.52 »

I had the exact same problem as I am loading literal animations for my loading page (Imma kill past me)

Code
//preloads images given through pathname and runs the callback once preloaded all images
function preloadImages(path, files, callback) {
    let images = [];
    let loaded = 0;

    files.forEach((file, index) => {
        let img = new Image();
        img.src = path + file;
        img.onload = () => {
            loaded++;
            if (loaded === files.length && callback) {
                callback(images);
            }
        };
        images[index] = img;
    });

    return images;

//images being declared as an array here
Images = preloadImages(ImagePath, ImageFileNameArray, (frames) => {
//run code after all images has been loaded
}

I also add a warning beforehand for something unrelated to give the code some time to load the images
You can see the code in action here

EDIT
It seems that images are created in the html file so you might need to change a bunch of the code to make it work.
Melon's code is good. But It means you'll see the stars popping in then the lines being displayed rather than everything appearing all at once.
« Last Edit: September 28, 2025 @93.28 by MediocreMetastasis » Logged


Artifact Swap: Cheese StoneSideEyeDoggoDerp DoggoShocked DoggoSad DoggoHappy DoggoNeutral DoggoShocked SharaCool McgeeLasagnaAgent JerrySunny the Puppy
bodypoetic
Casual Poster ⚓︎
*
View Profile WWWArt


for thine is the kingdom of wire and bone
⛺︎ My Room
Itch.io: My Games
RSS: RSS

Guild Memberships:
Artifacts:
Joined 2025!
« Reply #3 on: October 01, 2025 @970.05 »

Amazing - thanks, both! :transport: I've gone with Melon's solution for now; I'll look into loading the images from Javascript when I have a spare moment.

You can see the code in action here

That's a v cool page! I love the panning effect, the high effort really paid off. :cheesy:
Logged

Quote
The prince chose to sleep on, and the princess chose to wake up. At the top of that tall tower, the princess bid farewell to the prince. No—she wasn’t the princess any longer. She quit being a “person (thing) ruled by someone”. The victory bells rang, but there was no “tower (rule)” beyond them now. She’d learned where freedom lay. [...]

The world (the stage) is free and wide.

Pages: [1] Print 
« previous next »
 

Melonking.Net © Always and ever was! SMF 2.0.19 | SMF © 2021 | Privacy Notice | ~ Send Feedback ~ Forum Guide | Rules | RSS | WAP | Mobile


MelonLand Badges and Other Melon Sites!

MelonLand Project! Visit the MelonLand Forum! Support the Forum
Visit Melonking.Net! Visit the Gif Gallery! Pixel Sea TamaNOTchi