Chart Js 可点击栏

2022-01-22 00:00:00 charts php javascript chart.js

我想让我的图表 js 栏可点击.我想添加点击功能,例如链接.不知道如何进行.已阅读文档 10 次...

I want to make my chart js bar clickable. I want to add click features such as links. No idea how to proceed. Have read documentation times 10...

<script> var ctx = document.getElementById('myChart').getContext('2d');


var myChart = new Chart(ctx, {
 type: 'bar',
 data: {
labels: ['Now', '-1h', '-2h', '-3h', '-4h', '-5h', '-6h', '-7h', '-8h', '-9h', '-10h', '-11h', '-12h', '-13h', '-14h', '-15h', '-16h', '-17h', '-18h', '-19h', '-20h', '-21h', '-22h', '-23h'],
datasets: [{
  label: 'Litraa',
  data: [<?php echo "$chart_readings[0]";?>, <?php echo "$chart_readings[1]";?>, <?php echo "$chart_readings[2]";?>, <?php echo "$chart_readings[3]";?>, <?php echo "$chart_readings[4]";?>, <?php echo "$chart_readings3[5]";?>, <?php echo "$chart_readings3[6]";?>, <?php echo "$chart_readings[7]";?>, <?php echo "$chart_readings[8]";?>, <?php echo "$chart_readings[9]";?>, <?php echo "$chart_readings[10]";?>, <?php echo "$chart_readings[11]";?>, <?php echo "$chart_readings[12]";?>, <?php echo "$chart_readings[13]";?>, <?php echo "$chart_readings[14]";?>, <?php echo "$chart_readings[15]";?>, <?php echo "$chart_readings[16]";?>, <?php echo "$chart_readings[17]";?>, <?php echo "$chart_readings[18]";?>, <?php echo "$chart_readings[19]";?>, <?php echo "$chart_readings[20]";?>, <?php echo "$chart_readings[21]";?>, <?php echo "$chart_readings[22]";?>, <?php echo "$chart_readings[23]";?>],
  backgroundColor: "rgb(255, 255, 255)"
}]
},
   options: {
    tooltips: {
        mode: 'label'
    }
}
});
/*Global settings*/
Chart.defaults.global.defaultFontColor = '#fff';
</script>

推荐答案

如果您使用的是chart.js 2.4+ 版本(可能更早),有一个onclick 事件非常有用.我在堆积条形图上使用它,所以它也应该适合你.您可以在文档中的常用图表配置下找到它.(见:https://www.chartjs.org/docs/latest/charts/bar.html#stacked-bar-chart)

If you are using chart.js version 2.4+ (maybe earlier), there is a onclick event that is very useful. I'm using it on a stacked bar chart, so it should work for you too. You can find it under common chart configuration in the documentation. (See: https://www.chartjs.org/docs/latest/charts/bar.html#stacked-bar-chart)

options:{
    onClick: graphClickEvent
}

function graphClickEvent(event, array){
    if(array[0]){
       foo.bar;
    }
}

希望这会有所帮助.

相关文章