更新工具提示数据而无需在 Canvasjs 中重新加载整个图表

Update tooltip data without reloading whole chart in Canvasjs

我想更新 canvas js 图表中的工具提示,而不需要重新加载整个图表。

let arr = this.graph_arr;
let a = [];
let b = [];

arr.map((val) => {
  val.data.map((val2) => {
    b.push({
      x: new Date(val2.date),
      y: val2.revenue,
      cn: val2.check_in,
      rp: val2.rev_par,
      arr: val2.avrr,
      adr: val2.avg_daily_rate,
      date: moment(val2.date).format('Do, MMMM'),
      day: moment(val2.date).format('dddd')

    })
  })

  a.push({
    type: "spline",
    name: val.channel_img.split('.')[0].toUpperCase(),
    markerSize: 1,
    showInLegend: true,
    dataPoints: b,
    label: val.channel_img,
  })
  b = [];
})

let chart = new CanvasJS.Chart("chartContainer", {
  animationEnabled: true,
  theme: "light2",
  axisY2: {
    valueFormatString: "1'%'"
  },
  axisY: {
    suffix: "%"
  },
  axisX: {
    gridThickness: 1,
    valueFormatString: "DD/MMM"
  },
  legend: {
    cursor: "pointer",
    itemclick: this.toogleDataSeries
  },
  toolTip: {
    shared: false,

    content: this.selected == 'arr' ?
      `<div style='\"'width: 210px;'\"'>ARR: {arr}, date: {date} </div>` :
      this.selected == 'adr' ?
      `<div style='\"'width: 210px;'\"'>ARR: {arr}, date: {date] </div>` : null,

    cornerRadius: '8'
  },
  data: a
});

chart.render();

我有这个自定义工具提示。我想从下拉列表中更改其中的数据而不重新加载。目前我正在使用 ternary operator 并重新加载图表。当用户 select 来自下拉列表时,我想更改工具提示内容而不重新加载。

您可以使用 showAtX method 以编程方式显示工具提示。下面是一个例子:

var chart = new CanvasJS.Chart("chartContainer", {
  title:{
    text: "Show Tooltip based on dropdown"
  },
  data: [
    {
      type: "column",
      dataPoints: [
        { x: 10, y: 71 },
        { x: 20, y: 55 },
        { x: 30, y: 50 },
        { x: 40, y: 65 },
        { x: 50, y: 95 },
        { x: 60, y: 68 },
        { x: 70, y: 28 },
        { x: 80, y: 34 },
        { x: 90, y: 14 }
      ]
    }
  ]
});


chart.render();

var xVal = document.getElementById("xVal");
//Pass dataPoints as option to drop-down     
for(var i=0; i<chart.options.data[0].dataPoints.length;i++){
  var xValOption = document.createElement("option");

  xValOption.text = chart.options.data[0].dataPoints[i].x = chart.options.data[0].dataPoints[i].x;
  xVal.appendChild(xValOption);
}


xVal.addEventListener( "change",  showTooltip);


//
function showTooltip(e){   
  if(xVal.value)
    chart.toolTip.showAtX(Number(xVal.value));
  else 
    chart.toolTip.hide();
}
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 80%; float: left"></div>
<div style="float: right; width: 15%">
    Show Tooltip for <select id="xVal">
      <option>Select</option>
    </select>
</div>