Search code examples
javascriptcanvasjs

Canvasjs library, dataPoints


I have code like this, if i add dataPoints: [{ x: 50, y: 280 },{ x: 60, y: 507 }] it works.

But in the code below, the [{ x: 50, y: 280 },{ x: 60, y: 507 }] is in the variable rss, it not working.

<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>

Solution

  • It's not working because rss is seen as a string, not as an array. You'll need to do something like this:

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