使用chart.js动态添加图表

时间:2015-02-13 12:34:40

标签: javascript charts chart.js

我尝试使用chart.js添加饼图。但是我没有在js文件中添加数据,而是需要使用HTML数据生成图表。这是我的HTML:

<div class="chart-container">
    <canvas width="160" height="160"></canvas>
    <ul class="chart-data">
        <li data-value="100" data-color="#ff4d4d">Legend One</li>
        <li data-value="20" data-color="#ff7171">Legend Two</li>
        <li data-value="80" data-color="#ff9797">Legend Three</li>
    </ul>
</div><!-- /chart-container -->

我需要每个图表检索它的兄弟图表数据。

这是我的js:

function pieChart2(){

    var chartContainer = $('.chart-container'),
        chartCanvas = chartContainer.find('canvas'),
        chartData = [];

    chartCanvas.each(function(){
        var $this = $(this),
            ctx = $this.get(0).getContext("2d");

        window.myDoughnut = new Chart(ctx).Doughnut(chartData, {
            segmentShowStroke : false,
            showTooltips: false,
            percentageInnerCutout : 55
        });
    });
};
pieChart2();

2 个答案:

答案 0 :(得分:0)

好吧无论如何我自己解决了。如果遇到同样的问题,这是其他答案。对不起,如果我的js有不良做法。我不是专业人士。

function pieChart2(){

    var chartContainer = $('.chart-container');

    chartContainer.each(function(index){
        var $this = $(this),
            canvas = $this.find('canvas'),
            ctx = canvas.get(0).getContext("2d"),
            chartData = [];

        $this.find('.chart-data').find('li').each(function(){
            var li = $(this);

            chartData.push({
                value: li.data('value'),
                color: li.data('color'),
                label: li.text()
            })
        });

        window.myDoughnut = new Chart(ctx).Doughnut(chartData, {
            segmentShowStroke : false,
            showTooltips: false,
            percentageInnerCutout : 55,
            legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
        });
        var legend = myDoughnut.generateLegend();
        $this.append(legend);
    });

};
pieChart2();

答案 1 :(得分:-1)

要为插入的动力学元素创建新图形,您可以创建DOM Observer。我在

中创建了一个小例子

&#13;
&#13;
	$(function () {
	  $('.graph').each(function(index, canvas) {
	    createGraph(
      	canvas, 
        $(canvas).data('labels'), 
        $(canvas).data('datasets'), 
        $(canvas).data('options')
      );
      $(canvas).data('renderizado', true);
	  });
    
    $(document).on('DOMNodeInserted', function(e) {
        if ($(e.target).hasClass('graph')) {
           createGraph(
             e.target, 
             $(e.target).data('labels'), 
             $(e.target).data('datasets'), 
             $(e.target).data('options')
           );
           $(e.target).data('renderizado', true);
        }
    });
    
    $('#adicionar').on('click', function () {
		  $('#graphs').append('<canvas width="400" height="250" class="graph" data-options=\'{"showLines": true}\' data-renderizado=false data-labels=\'["January","February","March","April","May","June","July"]\' data-datasets=\'[{"label":"My First dataset","fill":false,"lineTension":0.1,"backgroundColor":"rgba(75,192,192,0.4)","borderColor":"rgba(75,192,192,1)","borderCapStyle":"butt","borderDash":[],"borderDashOffset":0.0,"borderJoinStyle":"miter","pointBorderColor":"rgba(75,192,192,1)","pointBackgroundColor":"#fff","pointBorderWidth":1,"pointHoverRadius":5,"pointHoverBackgroundColor":"rgba(75,192,192,1)","pointHoverBorderColor":"rgba(220,220,220,1)","pointHoverBorderWidth":2,"pointRadius":5, "pointHitRadius":10,"data":[56, 55, 40, 65, 59, 80, 0]}]\'></canvas>');
			});
	});

	function createGraph (canvas, labels, datasets, options) {
		Chart.Line(canvas,{
	    data:{labels: labels, datasets: datasets},
	    options:options
	  });
	}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="graphs">
  <canvas width="400" height="250" class="graph" data-options='{"showLines": true}' data-renderizado=false
  		  data-labels='["January","February","March","April","May","June","July"]'
          data-datasets='[{"label":"My First dataset","fill":false,"lineTension":0.1,"backgroundColor":"rgba(75,192,192,0.4)","borderColor":"rgba(75,192,192,1)","borderCapStyle":"butt","borderDash":[],"borderDashOffset":0.0, "borderJoinStyle":"miter","pointBorderColor":"rgba(75,192,192,1)","pointBackgroundColor":"#fff", "pointBorderWidth":1,"pointHoverRadius":5,"pointHoverBackgroundColor":"rgba(75,192,192,1)","pointHoverBorderColor":"rgba(220,220,220,1)","pointHoverBorderWidth":2,"pointRadius":5, "pointHitRadius":10,"data":[65, 59, 80, 0, 56, 55, 40]}]'></canvas>
</div>
<input type="button" value="Add Data" id="adicionar">
&#13;
&#13;
&#13;