3

As stated in the docs, the width and height attributes are required for an SVG <image>.

Now, I just have an image URL. I do not know the graphics size. I would instead like to retrieve it with JavaScript.

As described in an HTML-related question, I can create an Image object and read the dimensions from there. However, this seems wasteful as (I presume) it loads the image from the specified URL just to get the size, in order to load it again in the SVG <image> element.

Is there a way to retrieve the PNG graphic size directly via the SVG <image> element, so I can assign it to the same element's width and height properties?

O. R. Mapper
  • 20,083
  • 9
  • 69
  • 114
  • 3
    It is not wasteful. The browser will cache the image. It won't normally be loaded twice. – Paul LeBeau May 10 '19 at 13:54
  • @PaulLeBeau: Well, that's obviously what happens "physically". I would have expected the call to appear twice in the network view (even though once answered by the cache), but apparently, that doesn't happen. – O. R. Mapper May 10 '19 at 14:11
  • Han, I was sure there were better dupe targets than this one, but can't find it right now. Anyway, yes, create an Image, that's gonna be the easiest. – Kaiido May 10 '19 at 14:15
  • 1
    @Kaiido: Thanks for the duplicate link; as so often, it was a matter of using the right search terms. – O. R. Mapper May 10 '19 at 14:16
  • 1
    Yes, and once again this one is hard for search engines, `svg + image +` *whatever* returns a load of false positives when you want things about ... – Kaiido May 10 '19 at 14:17
  • You don't necessarily have to create an SVG `` element. It's probably simpler to create an HTML `` instead.`var image = new Image(); image.onload = function(){ alert('width: ' + image.naturalWidth + ' and height: ' + image.naturalHeight); }; image.src = myImageUrl;` – Paul LeBeau May 10 '19 at 15:38
  • @PaulLeBeau: And how do I integrate that HTML ´` element in my SVG document? – O. R. Mapper May 10 '19 at 15:41
  • You don't actually have to have an actual `` element in your document. You create one in JS using `new Image()`. As per my code snippet. – Paul LeBeau May 10 '19 at 15:43
  • See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement – Paul LeBeau May 10 '19 at 15:43
  • Demo: https://jsfiddle.net/phfsuc9z/ – Paul LeBeau May 10 '19 at 15:50
  • @PaulLeBeau: Ah, well, then that's the solution I was referring to in the question by "create an Image object and read the dimensions from there". – O. R. Mapper May 10 '19 at 19:02

0 Answers0