Mero
Mero

Reputation: 763

Can i use animate() for SVG <path>?

Trying to use vanila animate() function for animating SVG <path> element

Path:

<path id="path1" fill="black" d="M30,30l 50,10 0,50"></path>

Js:

path1.animate([
    { d: `M30,30 l10,10 50,0` },
    { d: `M30,30 l60,10 50,20` },
    { d: `M30,30 l10,10 50,0` },
 ], {
    duration: 1000
})

Getting warn and none working:

Invalid keyframe value for property d: M30,30 l10,10 50,0 Invalid keyframe value for property d: M30,30 l60,10 50,20 Invalid keyframe value for property d: M30,30 l10,10 50,0

Upvotes: 2

Views: 511

Answers (1)

herrstrietzel
herrstrietzel

Reputation: 17240

js animate() is using the Web Animation API.
So you will need to wrap your d coordiantes in a path() function like in css path animations.

path.animate([
    { d: "path('M40 40 l10 10 50 0')" },
 ], {
    duration: 1000,
})

let path0 = document.getElementById("path0");

path0.animate([
   // { d: "path('M30,30l 50,10 0,50')" },
    { d: "path('M40 40 l10 10 50 0')" },
    { d: "path('M50,50 l60,10 50,20')"},
    { d: "path('M30,60 l10,20 50,0')" },
 ], {
    duration: 1000,
    iterations: Infinity
})
svg {
  width: 200px;
  display: inline-block;
  border: 1px solid red;
}

.pathAni {
  transition: 0.3s;
}

.pathAniCss {
  animation: dAni 3s forwards infinite;
}

@keyframes dAni {
  33% {
    d: path("M40 40 l10 10 50 0");
  }
  66% {
    d: path("M50,50 l60,10 50,20");
  }
  100% {
    d: path("M30,60 l10,20 50,0");
  }
}
<svg viewBox="0 0 100 100">
  <path class="pathAn0" id="path0" fill="black" d="M30,30l 50,10 0,50"></path>
</svg>

<svg viewBox="0 0 100 100">
  <path class="pathAniCss" id="path2" fill="black" d="M30,30l 50,10 0,50"></path>
</svg>

From W3C Docs: Web Animations; W3C Working Draft, 18 May 2021

The Web Animations model is intended to provide the features necessary for expressing CSS Transitions [CSS-TRANSITIONS-1], CSS Animations [CSS-ANIMATIONS-1], and SVG [SVG11]. As such, the use cases of Web Animations model is the union of use cases for those three specifications.

Check browser support for path()
Firefox caniuse report 2022:

Only supported on the clip-path and offset-path properties.

Some examples for testing browser support: Animate SVG Path Changes in CSS

Upvotes: 5

Related Questions