svg.js: how to move and rotate togther?

64 views Asked by At

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

1

There are 1 answers

0
Dallas On

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 the animate() 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 using translate(x, y), which allows the rotation translation to use the initial center and allows you to override the x and y position of the translation matrix.

Modifying the example you linked to, it would look like this:

ele = document.getElementById('svg_1');

// Important note: when translating, you are specifying an _offset_ not a coordinate
// Moves 200 to the right from current position
const x = 200;

// Moves 50 up from current position
const y = -50;

const timeline = new SVG.Timeline();

const svgRect = SVG(ele);
svgRect.timeline(timeline);

svgRect.animate(1000, 0, 'now').translate(x, y).loop();
svgRect.animate(1500, 0, 'now').rotate(360).loop();