簡體   English   中英

是否有可能獲得不在DOM中的圖像的高度/寬度?

[英]Is it possible to get the height/width of an image that's not in the DOM?

是否可以使用JavaScript(即不屬於DOM的圖像)獲取文件系統中圖像的高度和寬度? 或者我是否必須使用JavaScript將圖像注入DOM並以這種方式獲取尺寸?

我問,因為我正在編寫一個JavaScript方法來快速渲染由Raphaël生成的UI組件,它將三個圖像路徑作為方法參數的一部分。 然后將它們用於渲染上述UI組件,並且我需要圖像的尺寸以用於定位目的。

提前致謝。

我認為只要圖像已經加載就可以抓住寬度和高度 - 你不應該把它注入到DOM中。 例如:

var tmp = new Image();
tmp.onload = function() {
    console.log(tmp.width + ' x ' + tmp.height);
}
tmp.src = 'http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4';

您不一定能訪問“文件系統”,但您可以這樣做:

v = new Image();
v.onload = function() {
  alert("size: " + String(v.width) + 'x' + String(v.height));
};
v.src = "http://www.gravatar.com/avatar/96269f5a69115aa0e461b6334292d651?s=32&d=identicon&r=PG";

你會把它算作“添加到DOM”嗎?

您可以使用代碼下載圖像:

var img=new Image(),imgWidth,imgHeight;
img.onerror=img.onload=function(ev) {
  ev=ev||event;
  if(ev.type==="error") {
    imgWidth=imgHeight=-1; // error loading image resourse
  }
  else {
    imgWidth=this.width; // orimgWidth=img.width
    imgHeight=this.height; // imgHeight=img.height
  }
}
img.src="url_to_image_file";

是否可以使用JavaScript(即不屬於DOM的圖像)獲取文件系統中圖像的高度和寬度?

  • 沒有

或者我是否必須使用JavaScript將圖像注入DOM並以這種方式獲取尺寸?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM