我想使用CSS关键帧在容器中移动SVG元素。
如果我只有一个<circle />,则可以简单地在关键帧定义中使用cx/ cy属性。但是,如果我有一个任意组(<g />)怎么办?群组没有cx/ cy,并且px如果要使用CSS' ,似乎必须定义一个单位(如)transform: translate(x,y)。
MWE(如何为bar小组设置动画?):
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 { }Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
如果我想使用CSS的transform:translate(x,y),似乎我必须定义一个单位(如px)。
是的,这是真的,你确实如此。
viewbox但如果您已经在元素中声明了一个属性,那么这不会成为问题<svg>。
如果您声明了viewbox,1px将代表 1 个视图框单元。
工作示例:
svg {
padding: 5px;
width: 150px;
height: 150px;
border: 1px solid #000;
}
.foo {
fill: red;
transform: translate(10px, 10px);
animation-duration: 3s;
animation-iteration-count: infinite;
animation-name: moveFoo;
}
.bar {
transform: translate(90px, 10px);
animation-duration: 3s;
animation-iteration-count: infinite;
animation-name: moveBar;
}
.bar circle {
fill: blue;
}
.bar text {
fill: white;
font-family: monospace;
font-size: 5px;
text-anchor: middle;
}
@keyframes moveFoo {
0% {transform: translate(10px, 10px);}
50% {transform: translate(90px, 90px);}
100% {transform: translate(10px, 10px);}
}
@keyframes moveBar {
0% {transform: translate(90px, 10px);}
50% {transform: translate(10px, 90px);}
100% {transform: translate(90px, 10px);}
}Run Code Online (Sandbox Code Playgroud)
<svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<circle class="foo" r="5" />
<g class="bar">
<circle r="5" />
<text y="1">AB</text>
</g>
</svg>Run Code Online (Sandbox Code Playgroud)