Skip to content

Instantly share code, notes, and snippets.

@cloudshapes
Last active December 17, 2015 19:39
Show Gist options
  • Save cloudshapes/5661984 to your computer and use it in GitHub Desktop.
Save cloudshapes/5661984 to your computer and use it in GitHub Desktop.
Dotted Path Following the Mouse

Dotted Path Following the Mouse

Bit of a simple variation of Mike Bostock's Spline Transition.

The idea is to have a dotted line of x-points long follow the mouse around, and trail behind it. Essentially the code creates and appends a path element, then on every mouse move adds a new point to the list of points, drops an old point, and updates the path.

Simples!

<!doctype html>
<html lang="en">
<head lang=en>
<meta charset="utf-8">
<title>D3: Dotted Path Following the Mouse</title>
<style>
svg {
background: #ddd;
font: 10px sans-serif;
}
.line {
fill: none;
stroke: #000;
stroke-width: 1.5px;
stroke-dasharray: 2,5;
}
</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 10, right: 10, bottom: 20, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var npoints = 100;
var ptdata = [];
var line = d3.svg.line()
.interpolate("basis")
.x(function(d, i) { return d[0]; })
.y(function(d, i) { return d[1]; });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var svgagain = d3.select("body").select("svg")
.on("mousemove", function() { var pt = d3.mouse(this); tick(pt); });
var path = svg.append("g")
.append("path")
.data([ptdata])
.attr("class", "line")
.attr("d", line);
function tick(pt) {
// push a new data point onto the back
ptdata.push(pt);
// Redraw the path:
path
.attr("d", function(d) { return line(d);})
// If more than 100 points, drop the old data pt off the front
if (ptdata.length > npoints) {
ptdata.shift();
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment