I want to make the rect move and rotate togther, but the result is not as expected, so how to realize my requirement ?
var ele = document.getElementById('svg_1')
var btn = document.getElementById('testBtn');
var timeline = new SVG.Timeline();
var x = 200,y = 0;
// btn.addEventListener('click', () => {
const svgRect = SVG(ele);
svgRect.timeline(timeline);
svgRect.animate(5000, 0, 'now').dmove(x, y).loop();
svgRect.animate(1500, 0, 'now').rotate(360).loop();
// })
<script src="https://cdn.jsdelivr.net/npm/@svgdotjs/[email protected]/dist/svg.min.js"></script>
<svg width="800" height="600" style="border:1px solid lightblue;">
<rect width="50" x="100" y="50" height="50" fill="#ffff00" stroke="#000000" id="svg_1"></rect>
</svg>
this is my demo url: codepen.io/echolove38/pen/jOxoQpK
When you use the
rotate()method in SVG.JS, it applies a transformation matrix to rotate the element around its center. It appears as though, when using theanimate()method, it keeps the original center, even when you move the element, causing it to "orbit" around its initial position.The quickest solution is to change from using
move(x, y)to usingtranslate(x, y), which allows the rotation translation to use the initial center and allows you to override thexandyposition of the translation matrix.Modifying the example you linked to, it would look like this: