Skip to content

Instantly share code, notes, and snippets.

@takumifukasawa
Created November 4, 2020 14:00
Show Gist options
  • Save takumifukasawa/67cc6717c69686749e2b853e92d6056a to your computer and use it in GitHub Desktop.
Save takumifukasawa/67cc6717c69686749e2b853e92d6056a to your computer and use it in GitHub Desktop.
typescript: get image rect size
/**
* srcから縦横幅を取得する
*
* @export
* @param {string} src
* @returns {Promise<{ width: number; height: number }>}
*/
export default async function getImageSize(
src: string
): Promise<{ width: number; height: number }> {
return new Promise((resolve, reject) => {
const image = new window.Image();
const onload = () => {
resolve({
width: image.naturalWidth,
height: image.naturalHeight,
});
};
const onerror = () => {
reject();
};
image.onload = onload;
image.onerror = onerror;
image.src = src;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment