首页 > 解决方案 > 在 Chart.js 中复制对象

问题描述

在循环($.each)中收集参数后,我绘制了一个图表。字符串已组装,但不能那样工作

var PieData = company;

当我复制该行并直接粘贴时,它工作正常。

var PieData = [{value: 14, color: '#2bea4f', highlight:'#2bea4f', label: 'Cts group'},{value: 4, color: '#411820', highlight:'#411820', label: 'СБЕРГРУЗ'},{value: 18, color: '#3b53a4', highlight:'#3b53a4', label: 'Фаворит Экспресс'},{value: 3, color: '#698bb4', highlight:'#698bb4', label: 'Бечехан'},];

如何让它发挥作用?

源代码如下

    //-------------
//- PIE CHART -
//-------------
// Get context with jQuery - using jQuery's .get() method.

var pieChartCanvas = $('#pieChart').get(0).getContext('2d')
var pieChart       = new Chart(pieChartCanvas)

var company = "[";

$.each( obj, function( key, value ) {
    var col = randColor();
    company += "{value: " + value.countShip + ", color: '" + col + "', highlight:'" + col + "', label: '" + value.name + "'},";
});

company += "]";

//var PieData = company;

var PieData        = [{value: 14, color: '#2bea4f', highlight:'#2bea4f', label: 'Cts group'},{value: 4, color: '#411820', highlight:'#411820', label: 'СБЕРГРУЗ'},{value: 18, color: '#3b53a4', highlight:'#3b53a4', label: 'Фаворит Экспресс'},{value: 3, color: '#698bb4', highlight:'#698bb4', label: 'Бечехан'},];

var pieOptions     = {
    //Boolean - Whether we should show a stroke on each segment
    segmentShowStroke    : true,
    //String - The colour of each segment stroke
    segmentStrokeColor   : '#fff',
    //Number - The width of each segment stroke
    segmentStrokeWidth   : 2,
    //Number - The percentage of the chart that we cut out of the middle
    percentageInnerCutout: 50, // This is 0 for Pie charts
    //Number - Amount of animation steps
    animationSteps       : 100,
    //String - Animation easing effect
    animationEasing      : 'easeOutBounce',
    //Boolean - Whether we animate the rotation of the Doughnut
    animateRotate        : true,
    //Boolean - Whether we animate scaling the Doughnut from the centre
    animateScale         : false,
    //Boolean - whether to make the chart responsive to window resizing
    responsive           : true,
    // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
    maintainAspectRatio  : true,
    //String - A legend template
    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>'
}
//Create pie or douhnut chart
// You can switch between pie and douhnut using the method below.
pieChart.Doughnut(PieData, pieOptions);

标签: javascriptchart.jspie-chart

解决方案


您的问题有点不清楚,但通过简要查看您的代码,我发现您尝试使用 String 作为 JSON 对象。

尝试更换

var PieData = company;

var PieData = JSON.parse(company);

推荐阅读