浏览器获取图片宽高

2018-05-28  本文已影响0人  jiansheng

以获取百度logo为例。

function getImageRect(src) {
    return new Promise((resolve, reject) => {
        const image = new Image();
        image.src = src;
        if (image.complete) {
            resolve({
                width: image.width,
                height: image.height
            });
        } else {
            image.onload = function () {
                resolve({
                    width: image.width,
                    height: image.height
                });
            }
        }
        image.onerror = err => reject(err);
    });
}

var imgSrc = 'https://www.baidu.com/img/bd_logo1.png?where=super';
getImageRect(imgSrc).then(({ width, height }) => {
    console.log({ width, height }); // {width: 540, height: 258}
});
上一篇 下一篇

猜你喜欢

热点阅读