Skip to content

Instantly share code, notes, and snippets.

@reinson
Last active March 31, 2017 09: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 reinson/97c4cd077ac39c29148e223d15ac89a5 to your computer and use it in GitHub Desktop.
Save reinson/97c4cd077ac39c29148e223d15ac89a5 to your computer and use it in GitHub Desktop.
Path animation
license: mit

Built with blockbuilder.org

Playing with stroke-dasharray and stroke-dashoffset attributes to animate a path.

Line from Mike Bostock’s block. Gradient from Nadieh Bremer’s block.

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<svg>
<linearGradient id="gradient-rainbow-main" gradientUnits="userSpaceOnUse" x1="0%" y1="0%" x2="60%" y2="0%"><stop offset="0" stop-color="#EFB605"></stop><stop offset="0.06666666666666667" stop-color="#E9A501"></stop><stop offset="0.13333333333333333" stop-color="#E48405"></stop><stop offset="0.2" stop-color="#E34914"></stop><stop offset="0.26666666666666666" stop-color="#DE0D2B"></stop><stop offset="0.3333333333333333" stop-color="#CF003E"></stop><stop offset="0.4" stop-color="#B90050"></stop><stop offset="0.4666666666666667" stop-color="#A30F65"></stop><stop offset="0.5333333333333333" stop-color="#8E297E"></stop><stop offset="0.6" stop-color="#724097"></stop><stop offset="0.6666666666666666" stop-color="#4F54A8"></stop><stop offset="0.7333333333333333" stop-color="#296DA4"></stop><stop offset="0.8" stop-color="#0C8B8C"></stop><stop offset="0.8666666666666667" stop-color="#0DA471"></stop><stop offset="0.9333333333333333" stop-color="#39B15E"></stop><stop offset="1" stop-color="#7EB852"></stop></linearGradient>
</svg>
<script>
var points = [
[480, 200],
[580, 400],
[680, 100],
[780, 300],
[180, 300],
[280, 100],
[380, 400]
];
var svg = d3.select("svg")
.attr("fill","transparent")
.attr("stroke","url(#gradient-rainbow-main)")
.attr("width", 960)
.attr("height", 500);
var path = svg.append("path")
.data([points])
.attr("d", d3.line().curve(d3.curveCardinalClosed))
.attr("stroke-width",3)
var totalLength = path.node().getTotalLength();
var visibleLength = 300;
animatePath();
function animatePath(){
path.attr("stroke-dasharray",visibleLength + " " + totalLength)
.attr("stroke-dashoffset", visibleLength)
.transition()
.ease(d3.easeQuadInOut)
.duration(2000)
.attr("stroke-dashoffset", -totalLength)
.on("end", animatePath);
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment