Checking for multiple images loaded

后端 未结 7 2189
死守一世寂寞
死守一世寂寞 2021-02-20 09:26

I\'m using the canvas feature of html5. I\'ve got some images to draw on the canvas and I need to check that they have all loaded before I can use them.

I have declared

7条回答
  •  误落风尘
    2021-02-20 09:46

    The solution with Promise would be:

    const images = [new Image(), new Image()]
    for (const image of images) {
      image.src = 'https://picsum.photos/200'
    }
    
    function imageIsLoaded(image) {
      return new Promise(resolve => {
        image.onload = () => resolve()
        image.onerror = () => resolve()
      })
    }
    
    Promise.all(images.map(imageIsLoaded)).then(() => {
      alert('All images are loaded')
    })

提交回复
热议问题