S
S
Shimpanze2018-02-08 07:32:35
JavaScript
Shimpanze, 2018-02-08 07:32:35

JavaScript: how to get image dimensions for output in code?

Good afternoon!
The tag needs to be configured and returned <img src="..." width="..." height="..." />.
I do it like this:

// создаю объект
var img = new Image();

// как только изображение загружено, можно прочитать его ширину и высоту
img.onload = function() {
    var width  = this.width,
        height = this.height;
};

img.src = url;

Question: how can I wait here (outside this function img.onload = function() {...}) when the image is exactly loaded and its dimensions are exactly obtained and ONLY THEN configure and return the tag <img />?
return '<img width="' + ??? width ??? + '" height="' + ??? height ??? + '" src="' + url + '"';

Whatever I do, I get either "undefined" or "0". Apparently return, it works faster than the image is loaded.
I will be grateful for help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2018-02-08
@Stalker_RED

how can I wait here (outside this function img.onload = function() {...}) when the image is exactly loaded
But... after all... the load event is specially made to show when the image is loaded. You want something weird.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question