使用 chart.js 动态添加图表

Dynamically add charts with 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();

好吧反正我自己解决了。如果有同样的问题,这里是其他人的答案。对不起,如果我的 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();

要为插入的动态元素创建新图表,您可以创建一个 DOM 观察者。我用

中的示例创建了一个 fiddle

 $(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
   });
 }
<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">