4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

最新の JavaScript で Image を読み込む方法

Posted at

JavaScript の HTMLImageElement オブジェクトは多くの場合、非同期で画像を読み込みます。

(decoding プロパティの値によって同期して読み込むことも可能ですが、非同期の方が効率よく画像を扱えるため、本記事では説明しません。)

JavaScript では元々非同期の処理はコールバック関数を用いる必要がありました。

const image = new Image();
image.onload = () => {
    // ... image ...
};
image.onerror = event => {
    // ... event ...
};
image.src = 'image.png';

Promise, async, await の追加によって、コールバック関数をラップして分かりやすく書くことができるようになりました。

const loadImage = src => new Promise((resolve, reject) => {
    const image = new Image();
    image.onload = () => resolve(image);
    image.onerror = event => reject(event);
    image.src = src;
});

const image = await loadImage('image.png');
// ... image ...

decode() メソッドの追加によって、new Promise() を書かずに Promise で扱えるようになりました。

const loadImage = async src => {
    const image = new Image();
    image.src = src;
    await image.decode();
    return image;
};

const image = await loadImage('image.png');
// ... image ...

参考「HTMLImageElement: decode() メソッド - Web API | MDN

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?