I want to move SVG elements across their container using CSS keyframes.
If I had just a <circle />
, I could simply use the cx
/ cy
properties in the keyframe definition. But what if I had an arbitrary group (<g />
)? A group doesn't have cx
/ cy
, and it seems that I have to define a unit (like px
) if I wanted to use CSS' transform: translate(x,y)
.
MWE (how do I animate the bar
group?):
svg {
padding: 5px;
width: 150px;
height: 150px;
border: 1px solid #000;
}
.foo {
animation-duration: 3s;
animation-iteration-count: infinite;
animation-name: moveFoo;
}
.bar {
animation-duration: 3s;
animation-iteration-count: infinite;
animation-name: moveBar;
}
@keyframes moveFoo {
from {
cx: 10;
cy: 10;
}
to {
cx: 90;
cy: 90;
}
}
/* how to define this? */
@keyframes moveBar { }
<svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<circle class="foo" r="5" fill="red" />
<g class="bar" transform="translate(90 10)">
<circle r="5" fill="blue" />
<text
y="1"
text-anchor="middle"
fill="white"
font-family="monospace"
font-size="5">
AB
</text>
</g>
</svg>
Use animateTransform
to do this:
svg {
padding: 5px;
width: 150px;
height: 150px;
border: 1px solid #000;
}
<svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<circle class="foo" r="5" fill="red" />
<g id="bar" transform="translate(90 10)">
<circle r="5" fill="blue" />
<text
y="1"
text-anchor="middle"
fill="white"
font-family="monospace"
font-size="5">
AB
</text>
</g>
<animateTransform xlink:href="#bar"
attributeName="transform"
type="translate"
from="90,10" to="90,90"
dur="2" repeatCount="indefinite"/>
</svg>
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