Skip to content

Instantly share code, notes, and snippets.

@beemyfriend
Created May 3, 2017 04:32
Show Gist options
  • Save beemyfriend/bf8481430ba48061ebabf0a87b68936b to your computer and use it in GitHub Desktop.
Save beemyfriend/bf8481430ba48061ebabf0a87b68936b to your computer and use it in GitHub Desktop.
Figuring out path tweening....
<head></head>
<body>
<body id = 'test'></body>
<script src = 'https://d3js.org/d3.v4.js'></script>
<script>
var height = 500,
width = 500,
symbol_size = 200,
animationDuration = 2000;
var diamond_generator = d3.symbol()
.type(d3.symbolDiamond)
.size(symbol_size);
var star_generator = d3.symbol()
.type(d3.symbolStar)
.size(symbol_size);
var svg = d3.select('#test')
.append('svg')
.attr('height', height)
.attr('width', width);
var g = svg.append('g')
.attr('transform', 'translate(' + (width/2) + ',' + (height/2) +')' )
var data = [0, 75, 150];
g.selectAll('path')
.data(data)
.enter().append('path')
.attr('d', 'M 0 0, h 20, v 20, h -20, z')
.attr('transform', function(d){return 'translate(' + d + ',0)'; console.log(d)})
function pathTween(d1, precision) {
return function() {
var path0 = this,
path1 = path0.cloneNode(),
n0 = path0.getTotalLength(),
n1 = (path1.setAttribute("d", d1), path1).getTotalLength();
// Uniform sampling of distance based on specified precision.
var distances = [0], i = 0, dt = precision / Math.max(n0, n1);
while ((i += dt) < 1) distances.push(i);
distances.push(1);
// Compute point-interpolators at each distance.
var points = distances.map(function(t) {
var p0 = path0.getPointAtLength(t * n0),
p1 = path1.getPointAtLength(t * n1);
return d3.interpolate([p0.x, p0.y], [p1.x, p1.y]);
});
return function(t) {
return t < 1 ? "M" + points.map(function(p) { return p(t); }).join("L") : d1;
};
};
}
function diamonds(){
g.selectAll('path')
.transition().duration(animationDuration)
.attrTween('d', pathTween(diamond_generator(), 1))
.attr('transform', function(d){return 'translate(' + (-d) + ',0)'})
.on('end', function(){squares();})
}
function stars(){
g.selectAll('path')
.transition().duration(animationDuration)
.attrTween('d', pathTween(star_generator(), 1))
.attr('transform', function(d){return 'translate(' + (d - 50) + ', 100)'})
.on('end', function(){diamonds();})
}
function squares(){
g.selectAll('path')
.transition().duration(animationDuration)
.attrTween('d', pathTween('m 0 0, h 20, v 20, h -20, z', 1))
.attr('transform', function(d){return 'translate(' + d + ',0)'; console.log(d)})
.on('end', function(){stars();})
}
stars();
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment