Skip to content

Instantly share code, notes, and snippets.

@veltman
Last active December 18, 2020 08:49
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/a85019d4131ad549434a28a5eece252c to your computer and use it in GitHub Desktop.
Save veltman/a85019d4131ad549434a28a5eece252c to your computer and use it in GitHub Desktop.
Dynamic CSS line animation
<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
stroke-width: 2px;
fill: none;
}
</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 paths = svg.selectAll("path")
.data(generateLines(40, 300))
.enter()
.append("path")
.style("stroke", function(d, i){
return d3.interpolateRainbow(i / 40);
})
.attr("d", function(d){
return "M" + d.join("L");
});
paths.each(function(d){
d.len = this.getTotalLength();
});
var style = document.styleSheets[0];
paths.data().forEach(function(line, i){
var rule = style.insertRule("@keyframes dash" + i + "{}", 0),
start = "0," + line.len,
end = line.len + ",0";
style.cssRules[0].appendRule("0% { stroke-dasharray: " + start + "; } ");
style.cssRules[0].appendRule("50% { stroke-dasharray: " + end + "; } ");
style.cssRules[0].appendRule("100% { stroke-dasharray: " + start + "; } ");
});
paths.style("animation", function(d, i){
return "dash" + i + " 3s linear infinite";
});
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];
});
});
}
</script>
@alexjlockwood
Copy link

Hey Noah,

I've been studying your blocks a lot recently and they've inspired me to learn d3 myself. I read this article by Mike Bostock on how to create blocks but I was wondering if in addition to this you used any particular IDE when writing your own (i.e. to catch syntax errors early etc.)? Just figured I would ask... thanks a lot for sharing this great code. :)

Alex

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment