I wanted to animate a rectangle so that it follows a given path which worked thus far using animateMotion
. This is what I have got:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<g>
<rect height="40" width="40" style="fill:#777; stroke:none;"/>
<animateMotion fill="freeze" path="M 0 0 Q 190 160 150 70 T 200 150 T 300 200 T 200 200" dur="3.14159s" repeatCount="indefinite"/>
</g>
<path d="M 0 0 Q 190 160 150 70 T 200 150 T 300 200 T 200 200" style="fill:none;stroke:#F00;stroke-width:5"/>
Now my question: How do I get the rectangle to follow the path (already achieved) with the center of the rectangle (20 20
) always being on the path? Can this be achieved with the means SVG offers?
Sure, just add a transform to the rect.
html, body, svg {
height: 100%;
width: 100%;
}
<svg>
<g>
<rect transform="translate(-20,-20)" height="40" width="40" style="fill:#777; stroke:none;"/>
<animateMotion fill="freeze" path="M 0 0 Q 190 160 150 70 T 200 150 T 300 200 T 200 200" dur="3.14159s" repeatCount="indefinite"/>
</g>
<path d="M 0 0 Q 190 160 150 70 T 200 150 T 300 200 T 200 200" style="fill:none;stroke:#F00;stroke-width:5"/>
</svg>
The translate acts to move the rect origin from 0,0 to the rectangle centre.