attrTween with svg text element?

1,571 views
Skip to first unread message

bren

unread,
Sep 30, 2012, 2:08:37 PM9/30/12
to d3...@googlegroups.com
If I want to display a text animation from number X to number Y, where the animation goes X, X+1, X+2, ..., Y-1, Y in a certain number of seconds, what would be the best way to do this in d3?

I think I need to use a tweening method, but I can't seem to get it to work. I've tried modifying this, but can't seem to get it working.

Let's say I have: var num = d3.select("body").append("text").text(1000); Can I get that to increment to, say, 5000 one by one over a period of say 10 seconds?

Many thanks in advance, all.

Marco D. Adelfio

unread,
Oct 1, 2012, 12:33:05 AM10/1/12
to d3...@googlegroups.com
I've done this with a custom tween function, per the documentation:
https://github.com/mbostock/d3/wiki/Transitions#wiki-tween

A working example: http://jsfiddle.net/c5YVX/

Marco

bren

unread,
Oct 1, 2012, 4:22:05 PM10/1/12
to d3...@googlegroups.com
Ah, fantastic -- codes makes perfect sense; many thanks Marco!

Jon Davenport

unread,
Nov 26, 2013, 9:48:04 AM11/26/13
to d3...@googlegroups.com
This worked perfectly, but I am trying to style my numbers with commas and a dollar sign. Is there a regex way around this? I've written up a function that adds commas, but I can;t pass it to the tween function since it isn't a number.

This is my comma conversion function:

function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");

Jon Davenport

unread,
Nov 26, 2013, 10:14:35 AM11/26/13
to d3...@googlegroups.com
I figured it out. I used a formatter:

d3.select("#mediantext")
.transition()
.duration(500)
.ease('linear')
.tween("text", function() {
var i = d3.interpolate(this.textContent, sum);
return function(t) {
 this.textContent = '$' + d3.format(",")(Math.round(i(t)));
};
 })
Reply all
Reply to author
Forward
0 new messages