更改圆环图的颜色

时间:2017-06-08 15:11:53

标签: javascript jquery html css

HTML

<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>


<div class="col-md-5">
    <div class="exp"></div>
</div>

javascript进入页面

<script type="text/javascript">

      $( document ).ready(function() {

        function get_data() {
          var props = ["conto", "investimenti"];
          var out   = [];
          var saldo = document.getElementById('saldo').value;
          var invest = document.getElementById('invest').value;
          var totale = parseFloat(saldo)+parseFloat(invest);

          out.push({"name":props[0], "hvalue": Math.floor((parseFloat(saldo)/totale)*100)});
          out.push({"name":props[1], "hvalue": Math.floor((parseFloat(invest)/totale)*100)});
          /*
          for (var i = 0; i < props.length; i++) {
            out.push({"name":props[i], "hvalue": Math.floor(Math.random() * 100)});
          };
          */
          return out;
        }

        // init the pie
        $(".exp").donutpie();

        // update it with some fake data
        $(".exp").donutpie('update', get_data());

        // keep updating every x sec
        setInterval( function () {
          $(".exp").donutpie('update', get_data());
        }, 400);

      });

  </script>

外部js文件

(function ( $ ) {

    var DonutPie = function($self, options) {
        this.$self = $self;
        this.settings = $.extend( $.fn.donutpie.defaults, options );
    };

    DonutPie.prototype.display = function() {

        var radius = this.settings.radius / 2;

        this.svg = d3.select(this.$self[0])
            .append("svg")
            .attr("width", radius * 2)
            .attr("height", radius * 2)
            .append("g");

        this.svg.append("g")
            .attr("class", "slices");

        this.pie = d3.layout.pie()
            .sort(null)
            .value(function(d){
                return d.hvalue;
            });

        this.arc = d3.svg.arc()
          .outerRadius(radius * 0.8)
          .innerRadius(radius * 0.4);

        this.outerArc = d3.svg.arc()
          .innerRadius(radius * 0.9)
          .outerRadius(radius * 0.9);

        this.svg.attr("transform", "translate(" + radius + "," + radius + ")");

        var tpClass = this.settings.tooltipClass;
        if (!$('body').hasClass( tpClass )) {
            $('.' + tpClass).remove();
            d3.select("body")
                .append("div")
                .attr('class', tpClass )
                .style("position", "absolute")
                .style("z-index", "100")
                .style("visibility", "hidden")
                .text("");
        }

    };

    DonutPie.prototype.update = function(data) {

        // check if all the items has colors.
        var colors = d3.scale.category20().range();
        for (var i = 0; i < data.length; i++) {
            if( data[i]['color'] == undefined ) 
                data[i]['color'] = colors[i];
        };

        var tooltip = this.settings.tooltip;
        var tpClass = "." + this.settings.tooltipClass;
        var arc = this.arc;
        var slice = this.svg.select(".slices").selectAll("path.slice")
            .data(this.pie(data));
        //roba sopra

        slice.enter()
            .insert("path")
            .style("fill", function(d) { return d.data.color; })
            .attr("title", function(d) { return d.data.name + " " + Math.round(d.value) + "%"; })
            .attr("class", "slice")

            .on("mouseover", function (d) {


            if (tooltip) {
                if (d.id != "none") {
                    $(tpClass).html( d.data.name + " " + Math.round(d.value) + "%" );
                    $(tpClass).css("visibility", "visible");
                }
            }

        });

        slice   
            .transition().duration(1000)
            .style("fill", function(d) { return d.data.color; })
            .attr("title", function(d) { return d.data.name + " " + Math.round(d.value) + "%"; })
            .attrTween("d", function(d) {
              this._current = this._current || d;
              var interpolate = d3.interpolate(this._current, d);
              this._current = interpolate(0);
              return function(t) {
                return arc(interpolate(t));
              };
            });

        slice.exit()
            .remove();

    };

    $.fn.donutpie = function(option) {

        var $this = $(this);
        var $donutpie = $this.data("donutpie");

        if(!$donutpie) {
            // init the object
            var options = typeof option == "object" && option;
            $donutpie   = new DonutPie($this, options);
            $this.data("donutpie", $donutpie);
        }

        if (typeof option === 'string' && $.fn.donutpie.methods[option]) {
            $donutpie[option].apply($donutpie, Array.prototype.slice.call(arguments, 1));
        } else if ( typeof option === 'object' || !option ) {
            $donutpie.display.apply( $donutpie, option);
        } else {
            $.error( 'Method ' +  option + ' does not exist in DonutPie' );
        }

    };

    $.fn.donutpie.methods = {
        'display': 1, 
        'update': 1
    }

    $.fn.donutpie.defaults = {
      radius: 240,
      tooltip : true,
      tooltipClass : "donut-pie-tooltip-bubble"
    };

}( jQuery ));

我必须改变图表的颜色,但我不能这样做。我怎么能改变这两种颜色?我试图修改代码,但它不起作用。请有人伸出援手。

1 个答案:

答案 0 :(得分:0)

要更改图表的颜色,必须在传递给更新功能的对象文字中指定“颜色”属性。在您的情况下,此对象文字在get_data()返回时定义。

要向对象文字添加颜色属性,请使用逗号跟随上一个属性,然后使用颜色定义属性的名称:“#rrggbb”。

out.push({name:props[0], hvalue: Math.floor((parseFloat(saldo)/totale)*100), color:"#FF0000"}); //makes color red