Get width and height of an external image with Javacript

2

I want to save in some variables the height and width of an image that is loaded through Javascript (no libraries, plugins, frameworks, etc) using your url.

img[i].addEventListener('mouseover', function(){
    link = this.parentElement.href;
    var w, h;
    document.getElementById('thread').insertAdjacentHTML('afterbegin', '<div id="lightbox"><img src="' + link + '"></div>');
}, false);

Where the variable link is the text string of the url of the image, which I want to use to save the height and width of the image in the variables w and h with something similar to:

w = link.width;
h = link.height;
    
asked by akko 06.03.2017 в 07:53
source

1 answer

1

In this SOeng answer tells you 3 ways to do it.

Since you do not want jQuery, I recommend you use this:

First create an image and add an event load to show its values width and height but it is to be visual.

function getMeta(url){   
    var img = new Image();
    img.addEventListener("load", function(){
        alert( this.naturalWidth +' '+ this.naturalHeight );
    });
    img.src = url;
}

getMeta("http://www.imagen.com.mx/assets/img/imagen_share.png");
    
answered by 06.03.2017 в 08:10