Skip to content

Instantly share code, notes, and snippets.

@harrytruong
Forked from KoGor/README.md
Last active December 1, 2019 23:46
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 harrytruong/c97ceac36fe971486653be2173cba12a to your computer and use it in GitHub Desktop.
Save harrytruong/c97ceac36fe971486653be2173cba12a to your computer and use it in GitHub Desktop.
Marker animation along SVG <path> element with D3.js II

Marker animation along SVG "path" element with D3.js: animating "path" and marker movement synchronously.

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<head>
<title>SVG path animation</title>
<link href="style.css" rel="stylesheet">
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/queue.v1.min.js"></script>
</head>
<body>
<!-- start -->
<div id="pathAnimation">
<script src="pathFollowAnimation.js"></script>
</div>
<!-- end -->
</body>
</html>
queue()
.defer(d3.xml, "wiggle.svg", "image/svg+xml")
.await(ready);
function ready(error, xml) {
//Adding our svg file to HTML document
var importedNode = document.importNode(xml.documentElement, true);
d3.select("#pathAnimation").node().appendChild(importedNode);
var svg = d3.select("svg");
var path = svg.select("path#wiggle").call(transition);
var startPoint = pathStartPoint(path);
var marker = svg.append("circle");
marker.attr("r", 7)
.attr("id", "marker")
.attr("transform", "translate(" + startPoint + ")");
//Get path start point for placing marker
function pathStartPoint(path) {
var d = path.attr("d"),
dsplitted = d.split(" ");
return dsplitted[1];
}
function transition(path) {
path.transition()
.duration(7500)
.attrTween("stroke-dasharray", tweenDash)
.each("end", function() { /*d3.select(this).call(transition);*/ });// infinite loop
}
function tweenDash() {
var l = path.node().getTotalLength();
var i = d3.interpolateString("0," + l, l + "," + l); // interpolation of stroke-dasharray style attr
return function(t) {
var marker = d3.select("#marker");
var p = path.node().getPointAtLength(t * l);
marker.attr("transform", "translate(" + p.x + "," + p.y + ")");//move marker
return i(t);
}
}
}
path {
fill: none;
stroke: #000;
stroke-width: 1px;
}
circle {
fill: red;
}
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment