Pitfalls in SVG Positioning
Dennis Guse_Update_: SVGGraphicsElement.getTransformToElement() was removed from the current draft.
In difference to pixel-based images formats, like JPEG or PNG, do SVG images allow to add animations, can be programmed and can react to user input. If an SVG image is embedded in a webpage, such an image can be modified with JavaScript as needed. For example change the text, color or change position of elements in the image.
In SVG elements can be positioned with by setting their a) x/y-coordinates and b) using transform. Whereas the first just sets the coordinates relative to the current coordinate system of the object, transform modifies the coordinate system for all this object and all childs.
Positioning via coordinates only:
Positioning via transform=”translate(x, y)”:
Both images are rendered exactly the same and from a viewer’s perspective are therefore equal. However, those are not equal from a programmatic perspective they are not.
TL;DR: When you need to re-position SVG-elements, try to avoid transform.
Here is an example with three rectangles. id=”rect1” and id=”rect3” are positioned via coordinates whereas id=”rect2” and id=”rect2-inner” are positioned via transform(s).
Two functions are required without transform svg-object.getBBox() and with transform svg-object.getTransformToElement(svg-object). The first, returns the minimal rectangle that contains the current object including x/y-coordinates. The second, calculates the shift between the virtual coordinate systems due to transform.
In the end both approaches work, but applying transform in addition makes moving more complicated. And as their are nicer things to do than debugging SVGs - try to avoid transform or at least RTFM.
NOTE: For some SVGs (created with (Inkscape)[https://inkscape.org]), I had some trouble due to transform (getTransformToElement() always returned the same values although different transform were applied). Inkscape removes transform attributes, when grouping and then ungroup elements; x/y-coordinates are re-calculated appropriately.