LoginSignup
93
68

More than 5 years have passed since last update.

PromiseベースでImage().onloadする

Last updated at Posted at 2018-08-08

やりたいこと

JavaScriptで、画像の width/height が知りたいとき、以下のようにする。

const img = new Image();

img.onload = () => {
  console.log(img.width, img.height);
}
img.src = '画像のパス';

img.src にパスをつっこんで、読み込み完了したタイミングで onload が走る。
このとき、 onload で完了を待たずに img.width などとしても0が返される(読み込み完了前の値が返される)。

これを Promise ベースで書いて、 async/await や、 then/catch の構文で使えると便利なのでは。

結果

こう書ける。Imageに限らず、onloadにコールバック指定する系はだいたい書き換え可能。

new Promise((resolve, reject) => {
  const img = new Image();
  img.onload = () => resolve(img);
  img.onerror = (e) => reject(e);
  img.src = '画像のパス';
})

これで await でも then でも catch でもなんでも出来る

// 関数化
loadImage(src) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = (e) => reject(e);
    img.src = src;
  });
}

// then/catch
loadImage('なんか画像のパス').then(res => {
  console.log(res.width, res.height);
}).catch(e => {
  console.log('onload error', e);
});

// async/await
async function() {
  const res = await loadImage('なんか画像のパス').catch(e => {
    console.log('onload error', e);
  });
  console.log(res.width, res.height);
}
93
68
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
93
68