Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

javascript - loading an image on web browser using Promise()

I'am trying to learn how to make SuperMario in JavaScript from here Can someone explain flow of the below function LoadImage ?

function loadImage(url) {
        return new  Promise(resolve => {
            const image = new Image();
            image.addEventListener('load', () => {
                resolve(image);
            });
            image.src = url; 
        });
}

const canvas = document.getElementById('screen');
const context = canvas.getContext('2d');

context.fillRect(0,0,50,50);

loadImage('/img/tiles.png')
.then(image=>{
    context.drawImage(image,0,0);  // the function LoadImage returns a Promise with image object(which is  a constant)
// as parameter and if the promise is fulfilled then the image is drawn. 
/
});

EDIT

I do understand how to use => operator. Which is used to make length of functions smaller.

image.addEventListener('load', () => {
                resolve(image);

the above line means that the promise is fulfilled when image is loaded. So does this mean that the following line is executed and then the event listener is waiting for the image to be downloaded in client browser ?

image.scr = url;

The flow of the below function is a little fuzzy to me

function loadImage(url) {
        return new  Promise(resolve => {
            const image = new Image();
            image.addEventListener('load', () => {
                resolve(image);
            });
            image.src = url; 
        });

EDIT 2:

Okay, this was a stupid post. And yup as the IMAGE from url is loaded in the image object then Event listener fires up the resolve().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The code you are showing introduces an asynchronous primitive, Promise, which can be passed around and used to access a resource that hasn't been populated yet.

In this case, you want an Image that is fully loaded and has image data that you can use. However, you can't access the image data until a network request finishes that would fetch the image data.

For example, this won't work:

const img = new Image();
img.src = "example.com/house.jpg";
ctx.drawImage(img, 0, 0); // img isn't done loading yet

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...