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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…