Animating a value of a tag attribute

212 Views Asked by At

Is there a way to animate a value of dy attribute of SVG's tspan using JavaScript, ideally using Web Animations API?

The value of dy is known to be animatable using <animate /> element (as seen here):

<svg>
  <text x="30" y="30">FairBridge
    <animate attributeName="dy" from="0 0 0" to="0 -20 20" dur="1s" repeatCount="indefinite"/>
  </text>
</svg>

I am wondering if it's possible to convert that animation to JavaScript.

For context, I've been using KeyframeEffect for all my previous animations, and would prefer to use it to animate the attribute value too in order to keep the animations code consistent.

In case there's absolutely no way to use KeyframeEffect, how would one go about animating a generic value of a tag attribute?

1

There are 1 best solutions below

2
On

Only the presentation attributes can be animated using Web Animations API, because they are also CSS properties, XML attributes cannot.

In this example I can animate fill and rotate, but not x and dy. When I give the x property the wrong value (like '100' or 100) I get an error in the FireFox console -- strange when the right value has no effect. dy is just ignored.

var text1 = document.getElementById('text1');

var textKeyframes = new KeyframeEffect(
  text1, [{
      fill: 'red',
      rotate: '0deg',
      x: '0px',
      dy: '0px'
    },
    {
      fill: 'green',
      rotate: '90deg',
      x: '100px',
      dy: '100px'
    }
  ], {
    duration: 2000,
    fill: 'forwards'
  }
);

var textAnimation = new Animation(textKeyframes, document.timeline);

textAnimation.play();
<svg viewBox="0 0 800 200">
  <g transform="translate(100 100)">
    <text id="text1" text-anchor="middle" dominant-baseline="middle"
      font-size="30">FairBridge </text>
  </g>
</svg>