I have two SVG files: intial.svg and final.svg. I want to morph initial.svg onto final.svg on button click event. I have gone through the libraries suggested in this question but there is no clear documentation or example on how to achieve this specific morph. I have exported these animations from an XD prototype. I want to achieve a simple ease-in animation by specifying the initial state of an svg and the final state of the same svg. Any recommendations would be highly appreciated.
Asked
Active
Viewed 730 times
0
-
1you really need one svg file. You can morph the contents with SMIL or CSS animations. – Robert Longson Sep 24 '21 at 09:22
-
Most libraries only morph paths or single elements. There is no way the library can know which part of the initial svg should be mophed to which part of the final svg. Yu somehow have to tell it – Fuzzyma Sep 24 '21 at 15:47
1 Answers
0
If the SVGs are (or can be) drawn from the same paths, then I would suggest the NPM library svg-path-morph. It allows you to interpolate freely between an arbitrary number of SVG paths.
An example of its usage:
import { compile, morph } from 'svg-path-morph'
// Get the d attributes of the <path> elements you want to morph between
const happy = document.getElemenyById('happy').getAttribute('d')
const angry = document.getElemenyById('angry').getAttribute('d')
// Compile the morph base (average path embedding)
const compiled = compile([
happy,
angry
])
// Morph between the happy/angry faces
const slightlyAngry = morph(
compiled,
[
0.80, // 80% happy
0.20 // 20% angry
]
)
// Use the face is the d attribute of a <path> element
document.getElementById('the-face').setAttribute('d', slightlyAngry)

Anders Brams
- 1
- 1
-
Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline. – jasie Jun 30 '22 at 07:35
-