Skip to content

Instantly share code, notes, and snippets.

@veltman
Created July 11, 2017 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veltman/d67134d8963c5b8ccdbbc666f0e91181 to your computer and use it in GitHub Desktop.
Save veltman/d67134d8963c5b8ccdbbc666f0e91181 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
stroke-width: 1px;
fill: none;
stroke: #444;
}
</style>
<svg width="960" height="500"></svg>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var width = 960,
height = 500;
var svg = d3.select("svg");
var lines = generateLines(50, 100);
var lengths = svg.selectAll("path")
.data(lines)
.enter()
.append("path")
.attr("d", function(d){
return "M" + d.join("L");
})
.nodes()
.map(function(node, i){
return {
length: node.getTotalLength(),
gap: lines[i + 1] ? distanceBetween(lines[i][lines[i].length - 1], lines[i + 1][0]) : 0
};
});
svg.selectAll("path")
.remove();
var path = svg.append("path")
.attr("d", "M" + d3.merge(lines).join("L"));
var start = d3.merge(lengths.map(function(l, i){
return [0, l.length + l.gap];
}));
var end = d3.merge(lengths.map(function(l, i){
return [l.length, l.gap];
}));
var interpolator = d3.interpolateArray(start, end);
timer = d3.timer(function(t){
var progress = 2 * Math.min(t % 3000 / 3000, 1 - t % 3000 / 3000);
path.attr("stroke-dasharray", function(d){
return interpolator(progress);
});
});
function generateLines(numLines, pointsPerLine) {
return d3.range(numLines).map(function(i){
var amplitude = ((i + 1) / numLines) * height / 2;
return d3.range(pointsPerLine).map(function(j){
var progress = j / (pointsPerLine - 1);
return [progress * width, height / 2 + Math.sin(4 * Math.PI * progress) * amplitude];
});
});
}
function distanceBetween(a, b) {
var dx = a[0] - b[0],
dy = a[1] - b[1];
return Math.sqrt(dx * dx + dy * dy);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment