Thursday 10 December 2020

JavaScript SVG continously appending animated element to SVG element

I have SVG element and I'm dynamically with JavaScript creating Circle element with animateMotion element. Circle should dynamically follow along with SVG path. I'm attaching endEvent listener to AnimateMotion element so after completing animation, created Circle element should be removed from DOM and whole process should start again. It works fine for first animation, but not for another iterations. Code is below - where I made mistake?

const test = document.getElementById('test');

function createAnimation() {
  const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
  const animation = document.createElementNS('http://www.w3.org/2000/svg', 'animateMotion');

  circle.setAttributeNS(null, 'r', '8');
  circle.setAttributeNS(null, 'fill', '#00F');

  animation.setAttributeNS(null, 'dur', '2s');
  animation.setAttributeNS(null, 'path', "M20,50 C20,-50 180,150 180,50 C180-50 20,150 20,50 z");

  circle.appendChild(animation);
  test.appendChild(circle);

  animation.addEventListener('endEvent', () => {
    circle.parentElement.removeChild(circle);
  });

  return new Promise((resolve) => {
    animation.addEventListener('endEvent', () => {
      resolve();
    });
  });
}

(async() => {
  while (true) {
    await createAnimation();
  }
})();
<svg id="test" viewBox="0 0 200 100" xmlns="http://www.w3.org/2000/svg">
  <path fill="none" stroke="lightgrey"
    d="M20,50 C20,-50 180,150 180,50 C180-50 20,150 20,50 z" />
</svg>


from JavaScript SVG continously appending animated element to SVG element

No comments:

Post a Comment