Skip to content

Instantly share code, notes, and snippets.

@MrHen
Last active April 9, 2016 16:33
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 MrHen/d3c98f99f1888e4079047160edbf62a0 to your computer and use it in GitHub Desktop.
Save MrHen/d3c98f99f1888e4079047160edbf62a0 to your computer and use it in GitHub Desktop.
D3 Text Interpolation
height: 500
license: MIT
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.16/d3.min.js"></script>
<script src="script.js"></script>
</body>
</html>
var height = 400;
var width = 400;
var points = [{
x: 250,
y: 250
},{
x: 100,
y: 100
}];
d3.interpolators.push(interpolateText);
var drag = d3.behavior.drag()
.on("dragstart", function(d, i) {
d.origin = [d.x, d.y];
})
.on("drag", function(d, i) {
d.x += d3.event.dx;
d.y += d3.event.dy;
draw(d3.select(this));
})
.on("dragend", function(d, i) {
var prev = [d.x, d.y].join(", ");
d.x = d.origin[0];
d.y = d.origin[1];
delete d.origin;
var next = [d.x, d.y].join(", ");
var selection = d3.select(this)
.transition()
.duration(1000)
.call(draw);
selection
.select("text")
.tween("textTween", function() {
var i = d3.interpolate(prev, next);
return function(t) {
this.textContent = i(t);
}
});
});
var svg = d3.select("body")
.append("svg")
.attr("height", height)
.attr("width", width);
var points = svg.selectAll(".point")
.data(points);
var newPoints = points.enter()
.append("g")
.attr("class", "point")
.call(drag);
newPoints.append("circle")
.attr("r", 40)
newPoints.append("text")
.attr("text-anchor", "middle")
.attr("alignment-baseline", "middle");
points.call(draw);
function draw(selection) {
selection
.attr("transform", function(d, i) {
return "translate(" + [d.x, d.y] + ")"
})
selection
.select("text")
.text(function(d) {
return [d.x, d.y].join(", ");
});
return selection;
}
function interpolateText(a, b) {
var regex = /^(\d+), (\d+)$/;
var matchA = regex.exec(a);
var matchB = regex.exec(b);
if (matchA && matchB) {
var x = d3.interpolateRound(+matchA[1], +matchB[1]);
var y = d3.interpolateRound(+matchA[2], +matchB[2]);
return function(t) {
var result = [x(t), y(t)].join(", ");
return result;
};
}
}
body {
background: #1f78b4;
}
svg {
background: #a6cee3;
border: solid 1px #333;
border-radius: 1em;
display: block;
margin: 1em auto;
}
circle {
fill: #b2df8a;
stroke: #333;
}
text {
fill: #333;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment