d3js 将动画文本显示为饼图

乔治亚·桑布罗塔

我有 3 个加载动画的饼图。每个图表,里面有一个文本,百分比数字,加载一个图表跟随动画并从 0% 开始计数到 ​​tot%

我能够在一个饼图中显示文本,但是当我调整要从 3 个饼图中使用的代码时,我找不到显示 3 个文本的方法。我循环了 3 div 和 3% 的数字,我可以在控制台中看到正确的百分比数字,但是饼图内没有显示任何内容:/

我是 d3 的新手,所以它可能比我能看到的要容易得多。

app.numbers = {
    calcPerc : function(percent) {
      return [percent, 100-percent];
    },

    drawDonutChart : function(el, percent, width, height, text_y) {
      width = typeof width !== undefined ? width : 290; //width
      height = typeof height !== undefined ? height : 290; //height
      text_y = typeof text_y !== undefined ? text_y : "-.10em";

      var radius = Math.min(width, height) / 2;
      var pie = d3.pie().sort(null);

      var dataset = {
        lower: this.calcPerc(0),
        upper: this.calcPerc(percent)
      }
      //this.percents = percent;

      this.arc = d3.arc()
            .innerRadius(radius - 20)
            .outerRadius(radius);

      var svg = d3.select(el).append("svg")
            .attr("width", width)
            .attr("height", height)
            .append("g")
            .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

      var path = svg.selectAll("path")
            .data(pie(dataset.lower))
            .enter().append("path")
            .attr("class", function(d, i) { return "color" + i })
            .attr("d", this.arc)
            .each(function(d) { this._currentArc = d; }); // store the initial values

      // add text in the center of the donut
      this.text = svg.append('text')
                .attr("text-anchor", "middle")
                .attr("dy", text_y)
                .attr("d", percent)

      if (typeof(percent) === "string") {
        this.text.text(percent);
      } else {

        var self = this;
        var timeout = setTimeout( function () {
          clearTimeout(timeout);

          path = path.data(pie(dataset.upper)); // update the data
          path.transition().ease(d3.easeExp).duration('500').attrTween("d", function(a){
            var progress = 0;
            var format = d3.format(".0%");
            // Store the displayed angles in _currentArc.
            // Then, interpolate from _currentArc to the new angles.
            // During the transition, _currentArc is updated in-place by d3.interpolate.
            var i  = d3.interpolate(this._currentArc, a);
            var i2 = d3.interpolate(progress, percent);
            this._currentArc = i(0);

            return function(t) {
              $(self.text).each(function(){
                $(this).text( format(i2(t) / 100) );
              });
              return self.arc(i(t));
            };

          }); // redraw the arcs

        }, 200);
      }
    },

    init : function(){

      $('.donut').each( function() {
        var percent = $(this).data('donut');

        app.numbers.drawDonutChart(
          this,
          percent,
          190,
          190,
          ".35em"
        );
      })
    }
  }
}

// initialize pie on scroll
window.onscroll = function() {
  app.numbers.init();
}

网址:

<section class="row numbers section-bkg section-bkg--blue">
  <div class="container">
    <div class="col-xs-12 col-sm-4">
      <div class="donut" data-donut="42"></div>
    </div>
    <div class="col-xs-12 col-sm-4">
      <div class="donut" data-donut="12"></div>
    </div>
    <div class="col-xs-12 col-sm-4">
      <div class="donut" data-donut="86"></div>
    </div>
  </div>
</section>

知道我应该如何显示文本吗?我很确定问题出在这里:

$(self.text).each(function(){
  $(this).text( format(i2(t) / 100) );
});
杰拉尔多·费塔朵

尽管混合 jQuery 和 D3 从来都不是一个好主意(尽量避免它),但似乎这不是问题。问题似乎在于您正在使用先前分配的self.

一种解决方案(无需过多更改代码,当然有更好的重构方法)是基于当前获取文本<path>

var self2 = this;//this is the transitioning path
return function(t) {
    d3.select(self2.parentNode).select("text").text(format(i2(t) / 100));
    return self.arc(i(t));
};

这是您的代码(不含 jQuery):

var app = {};

var color = d3.scaleOrdinal(d3.schemeCategory10)

app.numbers = {
  calcPerc: function(percent) {
    return [percent, 100 - percent];
  },

  drawDonutChart: function(el, percent, width, height, text_y) {
    width = typeof width !== undefined ? width : 290; //width
    height = typeof height !== undefined ? height : 290; //height
    text_y = typeof text_y !== undefined ? text_y : "-.10em";

    var radius = Math.min(width, height) / 2;
    var pie = d3.pie().sort(null);

    var dataset = {
        lower: this.calcPerc(0),
        upper: this.calcPerc(percent)
      }
      //this.percents = percent;

    this.arc = d3.arc()
      .innerRadius(radius - 20)
      .outerRadius(radius);

    var svg = d3.select(el).append("svg")
      .attr("width", width)
      .attr("height", height)
      .append("g")
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    var path = svg.selectAll("path")
      .data(pie(dataset.lower))
      .enter().append("path")
      .attr("fill", function(d, i) {
        return color(i)
      })
      .attr("d", this.arc)
      .each(function(d) {
        this._currentArc = d;
      }); // store the initial values

    // add text in the center of the donut
    this.text = svg.append('text')
      .attr("text-anchor", "middle")
      .attr("dy", text_y)
      .attr("d", percent)

    this.text.text(percent);

    var self = this;

    path = path.data(pie(dataset.upper)); // update the data
    path.transition().ease(d3.easeExp).duration(1000).attrTween("d", function(a) {
      var progress = 0;
      var format = d3.format(".0%");
      // Store the displayed angles in _currentArc.
      // Then, interpolate from _currentArc to the new angles.
      // During the transition, _currentArc is updated in-place by d3.interpolate.
      var i = d3.interpolate(this._currentArc, a);
      var i2 = d3.interpolate(progress, percent);
      this._currentArc = i(0);

      var self2 = this;

      return function(t) {
        d3.select(self2.parentNode).select("text").text(format(i2(t) / 100));
        return self.arc(i(t));
      };

    }); // redraw the arcs
  },

  init: function() {

    d3.selectAll('.donut').each(function() {
      var percent = d3.select(this).node().dataset.donut;

      app.numbers.drawDonutChart(
        this,
        percent,
        190,
        190,
        ".35em"
      );
    })
  }
}

app.numbers.init();
<script src="https://d3js.org/d3.v4.min.js"></script>
<section class="row numbers section-bkg section-bkg--blue">
  <div class="container">
    <div class="col-xs-12 col-sm-4">
      <div class="donut" data-donut="42"></div>
    </div>
    <div class="col-xs-12 col-sm-4">
      <div class="donut" data-donut="12"></div>
    </div>
    <div class="col-xs-12 col-sm-4">
      <div class="donut" data-donut="86"></div>
    </div>
  </div>
</section>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章