Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js获取页面图片大小 #31

Open
tiodot opened this issue Feb 23, 2018 · 0 comments
Open

js获取页面图片大小 #31

tiodot opened this issue Feb 23, 2018 · 0 comments

Comments

@tiodot
Copy link
Owner

tiodot commented Feb 23, 2018

在js获取图片真实尺寸的方式:

dom属性

对应每一个图片标签img都会有width和height表示其宽高,这两个是属性描述的是图片实际展示尺寸,可以根据视觉效果动态变更。既然可以获取渲染尺寸,当然还有两个属性表示其原始尺寸:naturalWidth和naturalHeight。这两个属性因为描述的图片原始大小,故不可修改。而且除了IE8以及之前IE版本外,各大浏览器均支持该属性。
例如demo图片:

let img = document.querySelector('img')
img.width // => 1322 浏览器窗口大小会影响展示的宽度值
img.naturalWidth  // => 1720 图片原始的宽度
img.height // => 513
img.naturalHeight // => 667

Image对象获取

也可以在js中构建一个image对象,在其onload事件中获取图片的高度和宽度:

function getImageSize(src) {
    let img = new Image();
    img.src = src;
    img.onload = function () {
        console.log('width:' + img.width + '; height:' + img.height);
    }
}

onload事件是图片完成加载之后触发,对于大图可以使用定时器获取图片大小:

function getImageSize(src) {
    var start_time = new Date().getTime();
    var img = new Image();
    img.src = src;
    var check = function(){
         // 简单判断,如果不为0,则表示已经返回
         if(img.width>0 || img.height>0){
	        let diff = new Date().getTime() - start_time;
	        console.log('width:' + img.width + '; height:' + img.height + '; time:' + diff);
	        clearInterval(set);
	}
    };
	 
    var set = setInterval(check, 40);
	 
    // 加载完成获取宽高
    img.onload = function(){
	    var diff = new Date().getTime() - start_time;
	    console.log('width:' + img.width + '; height:' + img.height + '; time:' + diff);
    };
}
 // 获取一个较大的图片
getImageSize('http://b.zol-img.com.cn/desk/bizhi/image/2/2560x1600/1365477614755.jpg')

参考

1、JS快速获取图片宽高的方法
2、html规范

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant