获取图像的宽度和高度,而不将其保留在页面上

时间:2019-01-28 09:35:53

标签: javascript jquery

不需要 DOM内的图像,但是需要来获取其尺寸。

尝试通过以下方式创建临时img元素:

let src = 'images/01.jpg';
let img = document.createElement('img');
img.src = src;
let w = img.naturalWidth;
let h = img.naturalHeight;
console.log(w); // 0
console.log(h); // 0
$(img).remove();

结果为00。实际尺寸为1349250

如何获取它们而不干扰现有页面的布局?

2 个答案:

答案 0 :(得分:2)

您必须等待图像加载:

let src = 'http://www.fillmurray.com/g/200/300';
let img = document.createElement('img');
img.onload = () => {
  console.log(img.naturalWidth);
  console.log(img.naturalHeight);
}
img.src = src;

在加载之前,浏览器无法知道图像的尺寸。如果需要其他功能中的尺寸,则必须使用回调参数返回承诺

let src = 'http://www.fillmurray.com/g/200/300';

// with a callback
const loadImgCallback = (url, callbackFn) => {
  let img = document.createElement('img');
  img.onload = () => { callbackFn(img); }
  img.src = src;
}

// with Promise
const loadImgPromise = url => new Promise((ok, fail) => {
  let img = document.createElement('img');
  img.onload = () => { ok(img); }
  img.onerror = fail;
  img.src = url;
});




/* === USAGE EXAMPLES === */
loadImgCallback(src, img => {
  console.log(`callback, naturalWidth: ${img.naturalWidth}`);
  console.log(`callback, naturalHeight: ${img.naturalHeight}`)
});

loadImgPromise(src).then(img => {
  console.log(`Promise, naturalWidth: ${img.naturalWidth}`);
  console.log(`Promise, naturalHeight: ${img.naturalHeight}`)
});

由您决定要选择哪种解决方案。

答案 1 :(得分:1)

只需将其分配给图像对象并加载图像:)

let src = 'https://images.pexels.com/photos/428338/pexels-photo-428338.jpeg';
var img = new Image();
//img = document.createElement('img');
img.src = src;
img.onload = function() {
  let w = img.naturalWidth;
  let h = img.naturalHeight;
  console.log(w); // 0
  console.log(h); // 0
}

//$(img).remove();