Чтобы получить размеры изображения в JavaScript, вы можете использовать различные методы. Вот несколько подходов:
-
Использование свойств
naturalWidthиnaturalHeightобъектаImage:var img = new Image(); img.src = 'image.jpg'; img.onload = function() { var width = this.naturalWidth; var height = this.naturalHeight; console.log('Image dimensions:', width, 'x', height); }; -
Использование HTML-элемента
imgи доступ к его свойствамwidthиheight:var imgElement = document.createElement('img'); imgElement.src = 'image.jpg'; imgElement.onload = function() { var width = this.width; var height = this.height; console.log('Image dimensions:', width, 'x', height); }; -
Загрузка изображения с помощью
XMLHttpRequestи чтениешириныивысотыиз ответа:var xhr = new XMLHttpRequest(); xhr.open('GET', 'image.jpg', true); xhr.responseType = 'blob'; xhr.onload = function() { var img = new Image(); img.src = URL.createObjectURL(xhr.response); img.onload = function() { var width = this.width; var height = this.height; console.log('Image dimensions:', width, 'x', height); }; }; xhr.send();
Эти методы позволяют получить ширину и высоту изображения в JavaScript.