我有一个CanvasJS图表,我想动态设置它的stripLine。

chart = new CanvasJS.Chart("chart",
    {
        backgroundColor: "rgba(0,0,0,0)",
        legend: {
            fontColor: "#FFF"
        },
        axisX: [{
            title: "Test axisX title",
            stripLines: [
                {
                    value: 250,
                    color: "#FF0000"
                }
            ],
        }],
        data: [] //Later add datapoints
    });


设置stripLine位置的函数:

var setVerticalLine = function (xPos) {
if (typeof chart !== 'undefined') {
    console.log(JSON.stringify(chart));  //debug info
    console.log("chart.axisX type: " + typeof chart.axisX); //debug info
    chart.axisX[0].stripLines[0].set("value", xPos);
}};


渲染后,我调用了该函数,但设置不成功。
错误:


  未捕获的TypeError:无法读取未定义的属性'0'...”
  调试信息:“ chart.axisX类型:未定义”。倾销图
  对象包含axisX:“ ...” axisX“:[{” title“:”测试axisX
  title“,” stripLines“:[{” value“:250,” color“:”#FF0000“}]}]] ......


当我在渲染的图表上看到带有标题和带状线的axisX时,怎么能找到undefined axisX?为什么我无法访问它并进行修改?有人可以帮我解决这个问题吗?

最佳答案

根据documentation,“应先绘制图表,然后才能使用set方法”。在您的情况下,调用setVerticalLine之前的渲染图应该可以正常工作。

这是工作代码:


var chart = new CanvasJS.Chart("chart", {
  backgroundColor: "rgba(0,0,0,0)",
  legend: {
    fontColor: "#FFF"
  },
  axisX: [{
    title: "Test axisX title",
    stripLines: [
      {
        value: 250,
        color: "#FF0000"
      }
    ],
  }],
  data: [] //Later add datapoints
});

chart.options.data.push({type: "line", dataPoints: [{x: 200, y: 100}, {x: 300, y: 50}]}); //Dummy datapoints
chart.render();// Render Chart before using set method

var setVerticalLine = function (xPos) {
  if (typeof chart !== 'undefined') {
    chart.axisX[0].stripLines[0].set("value", xPos);
  }
};

setVerticalLine(220); //Update Stripline value to 220

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chart" style="height: 260px; width: 100%;"></div>

关于javascript - CanvasJS图表axisX未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52346222/

10-09 22:28