Skip to content

Instantly share code, notes, and snippets.

@veltman
Last active February 3, 2018 19:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save veltman/fa74a3aff8497e970454bb064cf8dfd1 to your computer and use it in GitHub Desktop.
Save veltman/fa74a3aff8497e970454bb064cf8dfd1 to your computer and use it in GitHub Desktop.
Seamless animated dash

Animating a path's dashed stroke using stroke-dasharray and stroke-dashoffset, similar to this example. This version ensures that there's no little "seam" at the end of a closed path by dynamically setting the dash array and the animation keyframe to a factor of the computed path length.

stroke-dashadjust might make this easier eventually.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<style>
path {
fill: none;
stroke: black;
stroke-width: 2px;
-webkit-animation: move 0.4s infinite linear;
-moz-animation: move 0.4s infinite linear;
animation: move 0.4s infinite linear;
}
@-webkit-keyframes move {
0% {
stroke-dashoffset: 0;
}
}
@-moz-keyframes move {
0% {
stroke-dashoffset: 0;
}
}
@keyframes move {
0% {
stroke-dashoffset: 0;
}
}
</style>
</head>
<body>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="960" height="500">
<path d="M636.5,315c-0.4-18.7,1.9-27.9-5.3-35.9
c-22.7-25-107.3-2.8-118.3,35.9c-7,24.4,20.6,37.2,16,71c-4,29.6-30.8,60.7-56.5,61.1c-30.8,0.4-32.9-43.8-81.7-70.2
c-50.9-27.6-110.1-12.9-125.2-9.2c-66.1,16.4-82.2,56.9-109.2,47.3c-38-13.6-55.9-112.1-19.8-143.5c39-34,121.2,27.7,148.1-3.8
c18-21.1,3.1-74.3-25.2-105.3c-31.1-34.1-70.1-32.4-105.3-76.3c-8.2-10.2-16.9-23.8-15.3-39.7c1.2-11.4,7.5-23.3,15.3-29
c33.8-25,101.6,62.6,193.1,59.5c40.1-1.3,38.7-18.5,99.2-38.9c126.2-42.6,242.4-4.9,297.7,13c54.7,17.7,105.4,35,129.8,82.4
c13,25.3,22.9,67.7,4.6,87c-11.6,12.3-25.1,5.1-46.6,20.6c-2.8,2-28.9,21.4-32.1,49.6c-3.1,27.4,18.7,35,29,70.2
c8.8,30.1,8.5,77.8-18.3,99.2c-32.3,25.8-87,0.6-100-5.3c-69.6-32-67.2-88.4-73.3-109.2z"/>
</svg>
<script>
var path = document.querySelector("path"),
dash = path.getTotalLength() / 100,
offset = -dash * 2;
// Set the dasharray to something that divides evenly into the total length
path.style.strokeDasharray = dash + "," + dash;
// Add a 100% keyframe that offsets by one full dash group
[].slice.call(document.styleSheets).forEach(function(stylesheet){
[].slice.call(stylesheet.cssRules).forEach(function(rule){
if (rule.name === "move") {
rule.appendRule("100% { stroke-dashoffset: " + offset + "; }");
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment