javascript - 更改圆环图的颜色

标签 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 ));

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

最佳答案

要更改图表的颜色,必须在传递给更新函数的对象文字中指定“颜色”属性。在您的例子中,此对象文字是在 get_data() 的返回值中定义的。

要将颜色属性添加到对象字面量,请在前面的属性后跟一个逗号,然后使用颜色定义您的属性名称:“#rrggbb”。

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

关于javascript - 更改圆环图的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44439525/

相关文章:

javascript - 如何在 rails 和 webpack 的特定 View 中执行特定的 javascript 文件?

jQuery $.get 在 Internet Explorer 中什么也不做?

javascript - 如何通过变量名调用函数

javascript - 如何清除文本输入字段中的值?

javascript - onclick 按钮不调用函数

html - 文字阴影覆盖

javascript - 使用 Mongoose 更新子数组对象不起作用

javascript - 如何动态绑定(bind)ajax数据中的jquery静态数据

javascript - 在 meteor 中使用 Chart.js 我的图表未显示在浏览器屏幕上

css - 具有动态剩余高度和滚动条的 Div