Skip to content

Instantly share code, notes, and snippets.

@thehogfather
Created October 1, 2012 14:45
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 thehogfather/3812219 to your computer and use it in GitHub Desktop.
Save thehogfather/3812219 to your computer and use it in GitHub Desktop.
Sparkline draw
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<style>
path {
fill: none;
stroke: #000;
stroke-width: 3px;
}
circle {
fill: steelblue;
stroke: #fff;
stroke-width: 3px;
}
</style>
<script src="http://mbostock.github.com/d3/d3.js?2.7.2"></script>
<script src="./transition.js">
</script>
</body>
var w = 900,
h = 300,
pad = 40,
pathlength;
//create the data
var data = d3.range(50).map(function(d){
return d*36 * Math.PI/180;
});
//create horizontal and vertical scales
var hscale = d3.scale.linear()
.range([pad, w - pad])
.domain(d3.extent(data));
var vscale = d3.scale.linear()
.range([h - pad, pad])
.domain(d3.extent(data.map(function(d){
return Math.sin(d);
})));
var svg = d3.select("body")
.append('svg')
.attr('width', w)
.attr('height', h);
//line function is y = sin(x) where x is values from data in radians
var line = d3.svg.line().x(function(d){
return hscale(d);
}).y(function(d){
return vscale(Math.sin(d));
}).interpolate('cardinal');
//use the stroke-dasharray and stroke-dashoffset
//style properties to create animation of writing
var path = svg.append('path')
.data([data])
.attr('d', line)
.style('fill', 'none')
.style('stroke', 'black')
.style('stroke-dasharray', function(d){
pathlength = d3.select(this).node().getTotalLength();
return pathlength + "," + pathlength;
}).attr('stroke-dashoffset', pathlength);
var circle = svg.append('circle')
.attr('r', 5)
.style('stroke', 'white')
.style('stroke-width', 1.5)
.attr('transform', 'translate(0,' + line.y()(0) + ")");
transition();
function transition(){
var duration = 15000;
//animate the circle along the path and animate
//the stroke-dashoffset to uncover the path
circle.transition()
.duration(duration)
.attrTween('transform', translateAlong(path.node()));
path.transition().duration(duration)
.attr('stroke-dashoffset', 0);
}
function translateAlong(path){
var l = path.getTotalLength();
return function(d, i, a){
return function(t){
var p = path.getPointAtLength(t * l);
return 'translate(' + p.x + "," + p.y + ")";
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment