Search code examples
javascriptcanvasjs

Redirect to specific page after clicking on CanvasJS pie chart


I have the following diagram rendered by CanvasJS:

snapshot report

I want the 0.04% bar to be clickable. How can I achieve this?

Here's the code used to display the diagram:

    <script>
        window.onload = function () {
            var chart = new CanvasJS.Chart("chartContainer", {
                theme: "light2",
                animationEnabled: true,
                title: {
                    text: "Snapshots report status - <?php echo setDateOnChart() ?>"
                },
                data: [{
                    type: "pie",
                    indexLabel: "{y}",
                    yValueFormatString: "#,##0.00\"%\"",
                    indexLabelPlacement: "inside",
                    indexLabelFontColor: "#36454F",
                    indexLabelFontSize: 18,
                    indexLabelFontWeight: "bolder",
                    showInLegend: true,
                    legendText: "{label}",
                    dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
                }]
            });
            chart.render();
            }
        }
    </script>

Solution

  • Using the following link (thanks to @acbay), I resolved my problem. Here's the code I used:

        <script>
            window.onload = function () {
                var chart = new CanvasJS.Chart("chartContainer", {
                    theme: "light2",
                    animationEnabled: true,
                    title: {
                        text: "Snapshots report status - <?php echo setDateOnChart() ?>"
                    },
                    data: [{
    
                        click: function (e) {
                            if (e.dataPoint.label !== "Success") {
                                // it also checks that the dataPoint label isn't success
                                // since I don't want the user to click on the success part
                                window.open('http://localhost/...', "_blank");
                            }
                        },
    
                        type: "pie",
                        indexLabel: "{y}",
                        yValueFormatString: "#,##0.00\"%\"",
                        indexLabelPlacement: "inside",
                        indexLabelFontColor: "#36454F",
                        indexLabelFontSize: 18,
                        indexLabelFontWeight: "bolder",
                        showInLegend: true,
                        legendText: "{label}",
                        dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
                    }]
                });
                chart.render();
            }
        </script>