Img with svg src with no dimensions renders only a part
See original GitHub issueDescribe the bug
When rendering an svg which has no dimension attributes via src
, and applying imgSize
, the size does not apply to the resulting image. The same occurs when creating an <img>
with that same src and applying width/height on the image. The image appears cropped, with a crop box on the given dimensions, but only part of the original svg is rendered. Scaling also affects its entire container, not just the svg.
Rendering the same <img>
on a template works fine if width and height are supplied.
Expected behavior
The icon should be rendered in the given imgSize
, and not exceed those dimensions.
Details
I saw that applying color
, e.g. color: 'transparent'
to the Icon
resolves the issue. It seems that when a color is set, the image is redrawn on canvas using the correct scale. I managed to find the problem here:
https://github.com/openlayers/openlayers/blob/3b5e95b6c1f790c24ad1d632b3cba4202f26eb1c/src/ol/style/IconImage.js#L244-L251
Issue Analytics
- State:
- Created a year ago
- Comments:8 (5 by maintainers)
Top GitHub Comments
There are still some SVGs where browsers return the wrong image size, e.g. for https://upload.wikimedia.org/wikipedia/commons/f/fd/Ghostscript_Tiger.svg Chrome returns width and height as 150 x 150, which is too small, but it can be drawn and scaled correctly to a canvas of that size. By trial and error you can find a workable
imgSize
such as [400, 400] but is is easier to let OpenLayers use a canvas by specifyingcolor: 'transparent',
. However neither approach works with Firefox.In Firefox
image.naturalWidth
andimage.naturalHeight
are also zero anddrawImage()
does nothing even ifimage.width
andimage.height
are set or reset in the code.I have checked how Chrome handles these images.
is supposed to be equivalent to
but for unsized SVGs the image default width and height (which reflect the
naturalWidth
andnaturalHeight
) provide the aspect ratio, and the drawn image is sized to fit the canvas while maintaining aspect ratio, so is equivalent toThe syntax
only draws part of the image because Chrome considers the image to have dimensions as calculated above, so
does draw the whole image. But there seems to be nothing in the image properties to indicate whether it will be drawn in a normal way or whether this workaround is needed. So the only safe option is to draw to a canvas with dimensions matching the image width and height, and even that does not work in Firefox.