js获取图片原始宽高
warning:
这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
在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来获取图片的原始宽度和高度。
评论已关闭