4

I'm using d3 to animate text to show a user's progress towards completing a task. For example, if they've completed 32.51% of the task, the text will animate from 0% to 32.51% over 2 seconds or so.

To do this, I'm using d3's attrTween method on an svg text element in conjunction with d3.interpolate. The interpolation is working great, but I'm having a little trouble formatting the text. I'd like the text to always display 4 digits, so 0% = 00.00%, 4.31% = 04.31% etc. It would be nice to be able to do this without necessarily having to post process what the interpolator returns. In other words, without having to take the returned percentage and check to see if there are 4 digits and add zero padding on either side before placing it in the DOM.

As a test, I tried specifying the format that I would like by setting the a and b values to the interpolator like so d3.interpolate("00.00", "30.00"), but the final text is "30" with the trailing zeros cut off.

Any suggestions?

4

1 に答える 1

6

カスタム補間器を追加できます-ドキュメントd3.interpolatorsを参照してください。ドキュメントに記載されている例は、あなたの例に非常に近いものです。実際の変更は、出力形式を指定することだけです。この場合、次のようになります。

d3.format('05.2f'); // 0-padding, string width 5, 2 decimal places

これをドキュメントの例にプラグインします(正規表現も適切に変更し、パーセント記号を追加したことに注意してください)。

d3.interpolators.push(function(a, b) {
  var re = /^(\d\d\.\d\d)%$/, ma, mb, f = d3.format('05.2f');
  if ((ma = re.exec(a)) && (mb = re.exec(b))) {
    a = parseFloat(ma[1]);
    b = parseFloat(mb[1]) - a;
    return function(t) {
      return f(a + b * t) + '%';
    };
  }
});

d3.interpolate("00.00%", "30.00%")(1/5); // "06.00%"
d3.interpolate("00.00%", "30.00%")(1/3); // "10.00%"
于 2012-09-25T16:49:31.433 に答える