Skip to content

Instantly share code, notes, and snippets.

@kimxogus
Last active January 22, 2017 04:11
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 kimxogus/95a47d977aa8682fa74dba4279ff6234 to your computer and use it in GitHub Desktop.
Save kimxogus/95a47d977aa8682fa74dba4279ff6234 to your computer and use it in GitHub Desktop.
Path Token Animation
license: mit
var data = [{
x: 100,
y: 200
}, {
x: 200,
y: 100
}, {
x: 300,
y: 200
}, {
x: 400,
y: 100
}, {
x: 500,
y: 200
}, {
x: 400,
y: 300
}, {
x: 300,
y: 200
}, {
x: 200,
y: 300
}, {
x: 100,
y: 200
}];
<!DOCTYPE html>
<html lang="en">
<head>
<title>SVG - BBox</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://kimxogus.github.io/d3-zoomer/build/d3-zoomer.min.js"></script>
<style>
html, body {
margin: 0;
width: 100%;
height: 100%;
}
#svg {
width: 100%;
height: 100%;
}
#svg path {
stroke: black;
stroke-width: 1px;
fill: none;
}
</style>
</head>
<body>
<svg id="svg" xmlns="http://www.w3.org/2000/svg" version="1.1"></svg>
<script src="data.js"></script>
<script src="script.js"></script>
</body>
</html>
(function() {
'use strict';
var svg = d3.select("#svg");
var g = svg.append("g")
.call(d3.zoomer()); // d3-zoomer for easy pan-zoom behavior.
// define line.
var line = d3.line()
.curve(d3.curveBasis)
.x(function(d) {
return d.x;
})
.y(function(d) {
return d.y;
});
// draw line as path with data.
var path = g.append('path')
.attr('d', line(data));
// get Path DOM
var pathNode = path.node();
// get Total Length of path.
var pathLength = pathNode.getTotalLength();
// Animation duration 2 sec.
var duration = 2000;
// add token as circle.
var token = g.append("circle")
.attr("r", 5)
.attr("fill", "red");
var tick = 0;
function update() {
if (tick >= duration) {
tick -= duration;
}
tick += 1000 / 60; // 60 frames per one second.
var current = tick / duration;
var point = pathNode.getPointAtLength( current * pathLength);
token.attr("transform", "translate(" + [point.x, point.y] + ")");
requestAnimationFrame(update);
}
requestAnimationFrame(update);
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment