Animate drawing SVG path
by Spycez
HTML
<div style="margin: 0 0 20px 0">
<button id="button">Show SVG path</button>
</div>
<svg
width="150"
height="150"
viewBox="0 0 50 50"
xmlns="http://www.w3.org/2000/svg">
<path
pathLength="100"
fill="none"
stroke="#000000"
stroke-width="4"
d="M 10,10 L 40,10 L 40,40 L 10,40 z" />
</svg>
CSS
@keyframes my-animation {
from {
/* This 'from' could be removed. */
stroke-dashoffset: 100;
}
to {
stroke-dashoffset: 0;
}
}
svg path {
stroke-dasharray: 100;
stroke-dashoffset: 100;
animation-duration: 3s;
animation-timing-function: linear;
animation-fill-mode: forwards;
}
svg.animate path {
animation-name: my-animation;
}
JavaScript
const svgElement = document.getElementsByTagName("svg")[0];
const buttonElement = document.getElementsByTagName("button")[0];
buttonElement.addEventListener("click", () => {
svgElement.classList.toggle("animate");
});