0

I have an SVG which I want animated quite simply. One thing I want to animate is a ball which I want to move along a line. Here is what I tried:

const ball = document.getElementById('ball');
let i;
let j = 0;
for (i = 26.1; i <= 78.9; i+=0.1) { //26.1 and 78.9 are the maximum x positions of my ball.
  setTimeout(function(){ball.setAttribute("cx", `${i}`);}, j*1000);
  setTimeout(function(){ball.setAttribute("cy", `${1.12 * i + 0.12});}, j*1000);
  j++;
}

I tried several variants before understanding that the problem is: all is calculated in a fraction of a second and I find my ball in her final position on load time...

I also tried another variant with window.setInterval() but I then lose the advantage of a varying i to calculate my coordinates.

Thus, I am wondering: Is there any means to edit the same attribute several times with a loop with timing between each editing?

1 Answers1

0

Here's something to get you started:

var xPos = 0;
var speed = 1;

function loop() {
  document.getElementById("ball").style.left = xPos + "px";
  xPos += speed;
  if (xPos > 200) {
    speed = -Math.abs(speed);
  }
  if (xPos < 0) {
    speed = Math.abs(speed);
  }
  xPos += speed;
}
var interval = setInterval(loop, 20);
<svg height="100" width="100" id="ball" style="position:relative">
  <circle cx="50" cy="50" r="40" fill="red" />
</svg>
obscure
  • 11,916
  • 2
  • 17
  • 36