Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ergonomic Promise-based Image loading #7419

Open
josephrocca opened this issue Dec 14, 2021 · 2 comments
Open

Ergonomic Promise-based Image loading #7419

josephrocca opened this issue Dec 14, 2021 · 2 comments
Labels
addition/proposal New features or enhancements needs implementer interest Moving the issue forward requires implementers to express interest topic: img

Comments

@josephrocca
Copy link

Currently we need to write something like this (ignoring error handling):

let url = "https://example.com/image.png";
let img = new Image();
await new Promise(r => img.onload=r, img.src=url);
// img is ready to use

It would be useful if this could be done with a one-liner. Maybe something like this:

let img = await Image.load("https://example.com/image.png");

This isn't a proposal of any particular specifics of the API - I have no opinion there other than it being a one-liner to load an image. The above code snippet is just a placeholder example to get across the general idea. I'd hope that someone else with more experience would step in to fill in the concrete details.

The motivation is not so much about reducing lines of code as it is about making the intention more readable. The promisified onload approach is hacky and hard to read.

I wouldn't be surprised is something like this has been proposed before, but a quick couple of searches didn't surface anything, so apologies if I missed a previous/existing discussions/proposals.

@annevk
Copy link
Member

annevk commented Dec 14, 2021

See #127. new Image(url) doesn't exist though so that alone would not address the one-liner request.

@annevk annevk added addition/proposal New features or enhancements needs implementer interest Moving the issue forward requires implementers to express interest topic: img labels Dec 14, 2021
@Kaiido
Copy link
Member

Kaiido commented Dec 14, 2021

There is HTMLImageElement.decode() for bitmap images that does return a Promise (but it resolves with undefined).

Still

const img = new Image(url, { width, height, crossOrigin });
await img.decode();

could probably be a nice addition already.
Though thinking of it, Object.assign(new Image, {src, width, height, crossOrigin}) isn't that complex either.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
addition/proposal New features or enhancements needs implementer interest Moving the issue forward requires implementers to express interest topic: img
Development

No branches or pull requests

4 participants
@josephrocca @annevk @Kaiido and others