Skip to content

Instantly share code, notes, and snippets.

@danwild
Last active April 19, 2024 08:28
Show Gist options
  • Save danwild/c38a749177e34094358b0e21572e7297 to your computer and use it in GitHub Desktop.
Save danwild/c38a749177e34094358b0e21572e7297 to your computer and use it in GitHub Desktop.
D3 animate dashed paths to represent flow
<!--https://stackoverflow.com/a/39731911/1177832-->
<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
<style>
.node {
fill: #dddddd;
stroke: gray;
stroke-width: 4;
}
.flowline {
fill: none;
stroke: black;
opacity: 0.5;
stroke-width: 4;
stroke-dasharray: 10, 4;
}
</style>
</head>
<body>
<script>
var width = 960,
height = 500;
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height);
var ex1 = svg.append('g')
.attr('transform', 'translate(50 50)');
ex1.append('path')
.attr('class', 'flowline')
.attr('d', 'M100 100 L300 100');
ex1.append('path')
.attr('class', 'flowline')
.attr('d', 'M200 300 L300 100');
ex1.append('path')
.attr('class', 'flowline')
.attr('d', 'M200 300 L300 250');
ex1.append('path')
.attr('class', 'flowline')
.attr('d', 'M300 250 L100 100');
ex1.append('circle')
.attr('class', 'node')
.attr('cx', 100)
.attr('cy', 100)
.attr('r', 20);
ex1.append('circle')
.attr('class', 'node')
.attr('cx', 300)
.attr('cy', 100)
.attr('r', 20);
ex1.append('circle')
.attr('class', 'node')
.attr('cx', 200)
.attr('cy', 300)
.attr('r', 20);
ex1.append('circle')
.attr('class', 'node')
.attr('cx', 300)
.attr('cy', 250)
.attr('r', 20);
var ex2 = svg.append('g')
.attr('transform', 'translate(450 50)');
ex2.append('path')
.attr('class', 'flowline')
.attr('d', 'M100 100 S200 0 300 100');
ex2.append('path')
.attr('class', 'flowline')
.attr('d', 'M200 300 S200 200 300 100');
ex2.append('path')
.attr('class', 'flowline')
.attr('d', 'M200 300 S300 350 300 250');
ex2.append('path')
.attr('class', 'flowline')
.attr('d', 'M300 250 L100 100');
ex2.append('circle')
.attr('class', 'node')
.attr('cx', 100)
.attr('cy', 100)
.attr('r', 20);
ex2.append('circle')
.attr('class', 'node')
.attr('cx', 300)
.attr('cy', 100)
.attr('r', 20);
ex2.append('circle')
.attr('class', 'node')
.attr('cx', 200)
.attr('cy', 300)
.attr('r', 20);
ex2.append('circle')
.attr('class', 'node')
.attr('cx', 300)
.attr('cy', 250)
.attr('r', 20);
function animate(){
d3.select(this)
.transition()
.ease('linear')
.duration(1000)
.styleTween("stroke-dashoffset", function() {
return d3.interpolate(0, 14);
})
.each("end", animate);
}
d3.selectAll(".flowline")
.each(animate);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment