2

I try to make a link if a onclick event on a doughnut chart slice happens. My datasources are 3 arrays with labels, value, and the id for the url.

HTML:

<canvas id="pie-chart" style='display: none;'></canvas>

<!-- Php Arrays to JS -> PIE-CHARTDATA -->

<script type="text/javascript"> 

var chartIds = [[12,14,17,18]];

var chartValues = [[208.09,296.86,634.975,972.808]];

var chartLabels = [["BTC","AAPL","MSFT","ETH"]];

</script>

JS:

if (chartValues.length != 0 ) {
    document.getElementById("pie-chart").style.display= "block";
}
Chart.register(ChartDataLabels);

var chartValuesInt = [];
length = chartValues[0].length;
for (var i = 0; i < length; i++)
chartValuesInt.push(parseInt(chartValues[0][i]));

var data = [{
    data: chartValuesInt,
        chartIds,
    backgroundColor: [  
        "#f38000",
        "#5f44f5",
        "#333333",

    ],
    borderColor: "#000"
}];

var options = {
    borderWidth: 4,
    hoverOffset: 6,
    plugins: {
        legend: {
            display: false
        },
        tooltip: {
            enabled: false,
            
        },
        datalabels: {
            formatter: (value, ctx) => {
                let sum = 0;
                let dataArr = ctx.chart.data.datasets[0].data;

                dataArr.map(data => {
                    sum += data;
                });
                let percentage = (value*100 / sum).toFixed(2)+"%";

                return [ctx.chart.data.labels[ctx.dataIndex],
                percentage,   
                '$' + value ] ;
            },
            textAlign: 'center',
            color: '#fff',
            borderRadius: 50,
            padding:10,
            labels: {
                title: {
                    font: {
                        weight: 'bold',
                        size: '16px'
                    }
                },
            }  
        }
    },
    options:{
        onClick: (e, activeEls) => {
            let datasetIndex = activeEls[0].datasetIndex;
            let dataIndex = activeEls[0].index;
            let datasetLabel = e.chart.data.datasets[datasetIndex].label;
            let value = e.chart.data.datasets[datasetIndex].data[dataIndex];
            console.log("In click", datasetLabel,  value);
            //link to url with:[chartIds]
          }
    }
};

//IMAGE CENTER
const image = new Image();
image.src = 'img/pie-home2.png';

const plugin = {
  id: 'custom_canvas_background_image',
  beforeDraw: (chart) => {
    if (image.complete) {
      const ctx = chart.ctx;
      const {top, left, width, height} = chart.chartArea;
      const x = left + width / 2 - image.width / 2;
      const y = top + height / 2 - image.height / 2;
      ctx.drawImage(image, x, y);
    } else {
      image.onload = () => chart.draw();
    }
  }
};

var ctx = document.getElementById("pie-chart").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: chartLabels[0],
        datasets: data,
        chartIds
    },
    options: options,
    plugins: [plugin],
});

why does the onclick didn't work ?

how do i get the id with the right index from the slice where the event happens?

I searched already, but couldn't find a answer to these 2 questions.

NewInSpace
  • 23
  • 4
  • [This answer](https://stackoverflow.com/a/26258671/13181643) *may* help solve your needs. – Doc Jul 20 '22 at 12:11

1 Answers1

0

You onClick function does not work because you define an options object within your options object and put the onClick in there. This is not supported. When you remove the inner options layer it will work:

const options = {
  borderWidth: 4,
  hoverOffset: 6,
  plugins: {
    legend: {
      display: false
    },
    tooltip: {
      enabled: false,

    },
    datalabels: {
      formatter: (value, ctx) => {
        let sum = 0;
        let dataArr = ctx.chart.data.datasets[0].data;

        dataArr.map(data => {
          sum += data;
        });
        let percentage = (value * 100 / sum).toFixed(2) + "%";

        return [ctx.chart.data.labels[ctx.dataIndex],
          percentage,
          '$' + value
        ];
      },
      textAlign: 'center',
      color: '#fff',
      borderRadius: 50,
      padding: 10,
      labels: {
        title: {
          font: {
            weight: 'bold',
            size: '16px'
          }
        },
      }
    }
  },
  onClick: (e, activeEls) => {
    let datasetIndex = activeEls[0].datasetIndex;
    let dataIndex = activeEls[0].index;
    let datasetLabel = e.chart.data.datasets[datasetIndex].label;
    let value = e.chart.data.datasets[datasetIndex].data[dataIndex];
    console.log("In click", datasetLabel, value);
    //link to url with:[chartIds]
  }
};
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69