js获取图片原始宽高
warning:
这篇文章距离上次修改已过184天,其中的内容可能已经有所变动。
在JavaScript中,我们可以使用Image
对象的naturalWidth
和naturalHeight
属性来获取图片的原始宽度和高度。下面是两种不同的实现方法:
方法一:
var image = new Image();
image.src = 'image.jpg';
image.onload = function() {
var width = this.naturalWidth;
var height = this.naturalHeight;
console.log('图片的原始宽度:', width);
console.log('图片的原始高度:', height);
};
方法二:
var image = document.createElement('img');
image.src = 'image.jpg';
image.addEventListener('load', function() {
var width = this.naturalWidth;
var height = this.naturalHeight;
console.log('图片的原始宽度:', width);
console.log('图片的原始高度:', height);
});
这两种方法都首先创建一个Image
对象或img
元素,并设置其src
属性为要加载的图片的URL。然后,我们使用onload
事件或addEventListener
方法来监听图片加载完成的事件。在事件处理程序中,我们可以使用this.naturalWidth
和this.naturalHeight
来获取图片的原始宽度和高度。
评论已关闭