Skip to content

Instantly share code, notes, and snippets.

@veltman
Last active February 3, 2018 19:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save veltman/15345bbe4e4799a19a21b4acc88dcced to your computer and use it in GitHub Desktop.
Save veltman/15345bbe4e4799a19a21b4acc88dcced to your computer and use it in GitHub Desktop.
Animated subpath

Animating a portion of a larger path with a four-part stroke-dasharray pattern.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<style>
path {
fill: none;
stroke: #000;
stroke-width: 6px;
}
.bg {
stroke: #ccc;
stroke-width: 4px;
}
</style>
</head>
<body>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="960" height="500">
<path class="bg" d="M487.1,238.8c91,93,135,175.2,229.9,175.2s171.2-76.3,171.2-171.2S811.9,70.5,717,71.5c-94.9,1-130.1,70.5-216.3,167.3
C413.7,325,347.2,414,252.2,414S81,337.7,81,242.8S157.3,71.5,252.2,71.5S411.7,162.5,487.1,238.8z"/>
</svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var snake = d3.select("svg").append("path").attr("d", d3.select(".bg").attr("d")),
path = snake.node(),
totalLength = path.getTotalLength(),
snakeLength = totalLength * 0.25,
gap = totalLength - snakeLength,
duration = 3200;
d3.timer(function(t){
var pos = t % duration / duration,
dash;
if (pos < gap / totalLength) {
dash = "0," + (pos * totalLength) + "," + snakeLength + "," + totalLength;
} else {
dash = (totalLength * (pos - (gap / totalLength))) + "," + gap + "," + ((1 - pos) * totalLength) + "," + totalLength;
}
snake.attr("stroke-dasharray", dash);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment