Best way to move a group of SVG elements - svg

I'm looking for the best way (the faster, the cleaner...) to move a group of SVG elements. I have three ways in mind :
do a loop on all elements and, for each of us, change the x and y attributes
group all elements in a svg element and change its x and y attributes
group all elemnts in a g element and apply the method described here : https://stackoverflow.com/a/14036803/2019761
Do you have an idea please ?

You can move svg groups or elements with javascript
// translate svg element
function translate( _element , _x , _y )
{
var transform = _element.transform.baseVal.getItem(0);
var mat = transform.matrix;
mat = mat.translate( _x, _y );
transform.setMatrix( mat );
}
see it in action:
http://www.janvas.com/illustrators_designers_developers/projects/janvas2D_web/examples_EN.php?exampleName=ufo_animation_EN

I think that the better way is to move a group of elements.
If you look the example you can see that the ufo are translated
and the inner motor rotate inside of it.
(all moved elements are groups)
<g xmlns="http://www.w3.org/2000/svg" transform="matrix(1 0 0 1 -12.5067 69.4101)" id="ufo">
<g transform="matrix(1 0 0 1 0 -2.842170943040401e-14)">
<path transform="matrix(1 0 0 1 21.6 2.8)" width="92.34371368613222" height="91.4899957511011" stroke-width="0.83" stroke-miterlimit="3" stroke="none" fill="url(#_1_)" d="M46.1,0 C71.67,0 92… "/>
</g>
<g transform="matrix(0.5 0.86 -0.86 0.5 74.6 24.1)" id="motor">
<path transform="matrix(1 0 0 1 9.7 -2.2)" width="13.11" height="13.5849" stroke-width="0.88" stroke-miterlimit="3" stroke="none" fill="url(#_4_)" d="M6.55,2.8… "/>
</g>
</g>

Interacting with DOM methods involves JS <-> native code overhead. Browser implementers have been working hard to reduce this overhead, but it's never going to be free. If you're doing a lot of it, such as setting x and y on a lot of elements, you may start to see a significant performance impact. In this case setting positional properties just once on an <svg> or <g> container will likely help.
A more significant source of overhead is likely to be the work to repaint for the changes you make. If these changes are for a transform change, and if the transform's value changes multiple times in a short space of time, then most implementations will paint the content of the transformed SVG element into a cached offscreen surface and composite that surface instead of repainting each time. Recompositing can be a lot faster than repainting if the contents of the element are expensive to paint (say it contains a lot of children, or expensive filter effects), so if you're animating the transform of a <g> then you could well see much better performance.

Related

SVG group to child transforms

I have a group that has 2 or more SVG elements.
Group has a SVG matrix applied and the same apply for children.
Each element, including group can have any transformations applied through the matrix (rotate, skew, scale etc). Example of SVG with the group and 2 inner elements:
<g transform="matrix(0.679039, -0.734102, 0.734102, 0.679039, -21.7964, 262.861)">
<path transform="matrix(1, 0, 1.63636, 1, 82.9909, 49.1)" d="M92.35,45.6 A92.35,22.8 0 1 1 92.35016 45.6"></path>
<rect width="225.1" height="63.3" transform="matrix(0.742794, -0.66952, 0.66952, 0.742794, 242.258, 216.595)" rx="0"></rect>
</g>
I would like to do an ungroup function that removes the <g> element and place inner elements outside of g, but keeps all matrix transformations from group and their own transformations.
Tried multiple methods but they all have different issues where inner elements are not placed in the correct position or transformations are not copied.
The following seems to do something, but works for rotation only, if skew is applied - elements are totally different.
matrixMultiply(...matrices: DOMMatrix[]) : DOMMatrix {
let args = arguments, i = args.length, m = args[i-1];
while(i-- > 1) {
let m1 = args[i-1] as Matrix;
m = m1.multiply(m);
}
return m;
}
let groupMatrix = groupElement.transform.baseVal.getItem(0).matrix;
groupElement.childNodes.forEach(child => {
let childTransform = (child as SVGGraphicsElement).transform.baseVal.getItem(0),
childMatrix = childTransform.matrix,
childInverseMatrix = childMatrix.inverse();
let gm = matrixMultiply( childInverseMatrix, groupMatrix, childMatrix );
childTransform.setMatrix(gm);
});
You are making your life much too complicated. All you need to know is that a sequence of transform attributes, read in the direction of parent to child, has the same result as a sequence of transforms written left to right in one transform attribute:
<g transform="skewX(...)">
<path transform="matrix(...)" d="..." />
</g>
<!-- does the same transformation as -->
<path transform="skewX(...) matrix(...)" d="..." />
That simplifies your code to the following. If you want, you can compute the new transform value yourself by initializing a DOMMatrix from the transform strings. But why would you? The browser will do it for you anyway.
let groupTransform = groupElement.getAttribute('transform');
groupElement.childNodes.forEach(child => {
let childTransform = child.getAttribute('transform');
// not really needed...
let gm = new DOMMatrix(`${groupTransform} ${childTransform}`);
child.setAttribute('transform', gm.toString());
//...this would suffice
child.setAttribute('transform', `${groupTransform} ${childTransform}`);
});

Difference in length calculation for SVG text element

I am creating an SVG using the svg crate. To properly place a border around a <text> element, I calculate the length of the text beforehand using the rusttype crate.
However, my browser (Safari) seems to render the text with a different length.
The simplified version of my SVG is here:
<svg viewBox="0 0 210 297" xmlns="http://www.w3.org/2000/svg">
<g>
<path d="M105,20 L304,20 L304,77 L105,77 z" fill="none" stroke="black" stroke-width="1"/>
<text font-family="Arial" font-size="12" x="110" y="57">My extremely very, very, very, long Goal</text>
</g>
</svg>
I do calculate the length as found suggested here:
pub fn text_bounding_box(font: &Font, text: &str, size: f32) -> (u32, u32) {
let scale = rusttype::Scale::uniform(size);
let width = font
.layout(text, scale, rusttype::point(0.0, 0.0))
.last()
.map(|g| g.pixel_bounding_box().unwrap().max.x)
.unwrap_or(0);
let v_metrics = font.v_metrics(scale);
let height = (v_metrics.ascent - v_metrics.descent).ceil() + v_metrics.line_gap;
(width as u32, height as u32)
}
I ensured that the used font is Arial in both cases (when I calculate it, and for the SVG). At least, that's what I think.
My calculation yields a length of 189px. When inspecting the SVG with Safari, I see a width of ~213.14px.
Any suggestions are welcome.
I found a workaround to place a textLength attribute in the SVG, but I would at least like to understand the discrepancy. Thanks in advance.
Edit:
Rendered SVG without textLength attribute:
Rendered SVG with calculated textLength attribute:
There are several possible reasons for the discrepancies between measing text in two different libraries/engines.
Kerning differences
Ligature handling differences
On-screen font renderers often adjust glyph position to better align with screen pixels. Especially for small font sizes.
There are other potential font-specific features and variations that may be affecting rendering
Most likely is probably #3. Try setting font size to something big (eg. 100) to see if this is the case. You could also try experimenting with the CSS text-rendering property.

Which character can be eliminated in svg? Why is an arc rendered into a complete circle?

The logo of TV domain is svg, I found that its grammar is strange but no error is reported.
<path d="M19.67 43.46a9.62 9.62 0 110-.05z" fill="#e10e49"></path>
According to w3c standard, I think it should be written like this?
<path d="M19.67 43.46a9.62 9.62 0 1 1 0-.05z" fill="#e10e49"></path>
And why is this arc rendered as a complete circle?
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 119.19 75.7" height="75.7" width="119.19">
<path d="M19.67 43.46a9.62 9.62 0 110-.05z" fill="#e10e49"/>
</svg>
In Wikimedia Commons it looks like this
The SVG 1.1 specification helpfully includes a BNF for parsing. In there we have
elliptical-arc:
( "A" | "a" ) wsp* elliptical-arc-argument-sequence
elliptical-arc-argument-sequence:
elliptical-arc-argument
| elliptical-arc-argument comma-wsp? elliptical-arc-argument-sequence
elliptical-arc-argument:
nonnegative-number comma-wsp? nonnegative-number comma-wsp?
number comma-wsp flag comma-wsp? flag comma-wsp? coordinate-pair
...
flag:
"0" | "1"
So as soon as you read the 1 for the flag you're done and you move onto the next item. Whitespace between flags is optional (? means 0 or 1).
The arc is not a complete circle, the z completes it with a straight line but it's small and you don't notice it.

How to convert font size (in px) to the unit used in the document (mm) for svg

I have svg created in inkscape here.
The document size is in mm. For the 2 text fields, the font size is given like this:
style="...;font-size:31.420084px;..."
So it is given in px. Now I want the size of the font related to the document size.
But how should I convert the font-size in px to mm? I would need something like dpi, but the document does not specify anything.
In your case, your viewBox matches your document dimensions:
width="164.28572mm"
height="78.10714mm"
viewBox="0 0 164.28572 78.10714"
that means all unit less values are in mm. Just specify your font-size without units (or in your case when you use css just keep your document untouched and use px).
The confusing part is, that px in svg are always user units and not device pixels, for that reason, your font-size is already given in mm... so font-size:31.420084px in your document is equal to font-size:31.420084mm in a viewBox less document (where user units equal to device pixels)
<svg viewBox="0 0 100 20" width="100mm" height="20mm">
<text x="0" y="12" font-size="12px">12px</text>
</svg>
<svg >
<text x="0" y="12mm" font-size="12mm">12mm</text>
</svg>
Thats where it gets confusing. In the next example "1mm" is equal to 3.6 user units, but because 1 user unit equals 1mm in the real world, one svg mm equals 3.6 real mm ...
<svg viewBox="0 0 50 50" width="50mm" height="50mm">
<text x="0" y="5" font-size="1mm">font-size: 1mm</text>
<text x="0" y="10" font-size="3.6">font-size: 3.6</text>
</svg>
Units in SVG are a bit wired, but well defined...
The SVGLength Interface has a Method convertToSpecifiedUnits.
you can use that to convert between different units in SVG.
var l = svg.createSVGLength()
l.newValueSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PX, 12)
l.convertToSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_MM)
out1.innerHTML = l.valueAsString
svg {
width: 0;
height: 0
}
<svg id="svg">
</svg>
12px = <span id="out1"></span>
The standard DPI used in an SVG document is the standard DPI that is specified by the CSS standard. That is 96dpi, or 96 standard CSS pixels per inch.
There are 25.4 mm per inch. So to convert px to mm, the formula will be:
mm = 25.4 * (px / 96)
So if we plug your original 31.420084px into that formula, the result is 8.31mm.
Note that CSS doesn't take into account the real word DPI of the device that you are rendering to. It uses that fixed approximation of 96pixels per inch. So you can't rely on the fact that an element with size 96px or 25.4mm will actually be that size on screen, or when printed.

SVG semi-circles and Arc parameter disambiguation

As helpfully explained and demonstrated in this MDN article, SVG arcs are defined in a way that is a little tricky, especially when compared to the JS Canvas arcTo() method.
The problem arises when I want a semi-circle in my path. In a case like this, with an angle of 180°, the two possible circles overlap, and the "large-arc flag" becomes ambiguous because it's explained as "if the arc should be greater than or less than 180 degrees" - it doesn't specify what should happen if the angle is exactly 180 degrees.
Until now I've "resolved" this issue through simple trial-and-error. Take a guess, did the arc go the wrong way? Try changing a flag until it works. There's only four combinations after all, it doesn't take much work.
But I'd just like to further my understanding. In a case like this, how can I know ahead of time which way my arc will go? Is there an easy way to remember this information so I don't have to resort to trial-and-error?
And on a related note, what if I want my "arc" to be a full circle? In a case like this, there are infinitely many possible circles that meet the criteria of "passes through the starting/ending point (same point!) and has radius R", so is this resolvable at all, or should I stick to two 180° semi-circles instead?
Note that sweep-flag defines arc rotation direction. So for 180-degrees arc just choose needed semicircle with this flag. large-arc-flag doesn't influence in this case.
<svg width="325" height="325" xmlns="http://www.w3.org/2000/svg">
<path d="M 0 100
A 50 50, 0, 0, 0, 100 100
L 125 100 Z" fill="green"/>
<path d="M 200 100
A 50 50, 0, 0, 1, 300 100
L 325 100 Z" fill="green"/>
<path d="M 0 200
A 50 50, 0, 1, 0, 100 200
L 125 200 Z" fill="green"/>
<path d="M 200 200
A 50 50, 0, 1, 1, 300 200
L 325 200 Z" fill="green"/>
</svg>

Resources