Canvasjs库,dataPoints

时间:2017-09-07 10:00:59

标签: javascript canvasjs

我有这样的代码,如果我添加dataPoints: [{x:50,y:280},{x:60,y:507}]它有效。

但是在下面的代码中,[{x:50,y:280},{x:60,y:507}]在变量rss中,它不起作用。

<script type="text/javascript">
      window.onload = function () {

        var year = ('<?php echo $rs; ?>');

        var jsontoarray = JSON.parse(year);

        var props = Object.keys(jsontoarray);
        var rss = "[";
        for (var i = 0; i < props.length; i++) {
          rss += "{ x: " + props[i] +  ", y: " + jsontoarray[props[i]] + "},";
        }

        rss = rss.substr(0, rss.length - 1); //bỏ dấu , cuối cùng
        rss += "]";

          var chart = new CanvasJS.Chart("chartContainer", {
            title: {
              text: "Column Chart with Index Label and Data Point Width"
            },
            axisX: {
              interval: 10
            },
            dataPointWidth: 60,
            data: [{
              type: "column",
              indexLabelLineThickness: 2,
              dataPoints: rss
            }]
          });
        chart.render();
      }
    </script>

    <div id="chartContainer" style="height: 400px; width: 95%; margin: auto;"></div>

1 个答案:

答案 0 :(得分:1)

它不起作用,因为rss被视为字符串,而不是数组。 你需要做这样的事情:

var rss = [];
for (var i = 0; i < props.length; i++) {
    rss.push({
        x: props[i],
        y: jsontoarray[props[i]]
    });
}