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 you have an idea please ?
The SVG <g> element is used to group SVG shapes together.
The SVG format allows for the nesting of SVG graphics. It is possible for an “<svg>” elements, to be placed within another “<svg>” element.
Grouping in SVG using the <g> element works the same way. In this example we've grouped the elements of the body together, the elements of the head together, and then we grouped the two groups into one group with an id of bird .
The transform attribute defines a list of transform definitions that are applied to an element and the element's children. Note: As of SVG2, transform is a presentation attribute, meaning it can be used as a CSS property.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With