Skip to content

Instantly share code, notes, and snippets.



Last active Dec 17, 2015
What would you like to do?
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.


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