JSFiddle - React, Tailwind, and code Playground

by Gary Davies

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<!doctype html>
<html>
  <head>
  </head>
  <body>
  <div class="graph">
    <div class="section">
      <canvas id="chart_id" class="graph" width="auto" height="auto"></canvas>
    </div>
  </div>
 </body>
 </html>

JavaScript

function generateColour (rollover) {
  const hue = Math.random() * 360
  const saturation = 60 + Math.random() * 30 // start at 60, cap at 90, max is 100.
  const luminosity = 50 + Math.random() * 30 // start at 50, cap at 80, max is 100.
  if (rollover) {
    var colour = `hsl(${hue}, ${saturation}%, ${luminosity}%)`
    var rollover = `hsl(${hue}, ${saturation*0.5}%, ${luminosity*0.4}%)`
    return {colour, rollover}
  }

  return `hsl(${hue}, ${saturation}%, ${luminosity}%)`
}

total = 11076481;
ctx = document.getElementById('chart_id');

label =
  {labels: ["200","403","404"]};
  
data = 
  {datasets: [{"data":[10798225,41089,237167]},{"data":[12345,21345,32145]}],
  labels: label.labels}


options = {
  animation: {animateScale: true,
  						animationEasing: "easeOutBounce"},
  onClick: function(evt, element){
    var activePoints = ctx.parentNode.graph.getElementAtEvent(evt);
    console.log(activePoints[0]._model.label);
  },
  multiTooltipTemplate: "<%= label %>",
  legend: {
    labels: {
      generateLabels: function (chart) {
        var data = chart.data;
        var dataset = data.datasets[0]; // Note, only one dataset expected
        return Array.isArray(dataset.data) ? dataset.data.map(function (value, i) {
          return {
            text: data.labels[i] + ', ' + ((value / total) * 100).toFixed(2) + '%',
            fillStyle: (!Array.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[i]),
            hidden: !chart.isDatasetVisible(0),
            lineCap: dataset.borderCapStyle,
            lineDash: dataset.borderDash,
            lineDashOffset: dataset.borderDashOffset,
            lineJoin: dataset.borderJoinStyle,
            lineWidth: dataset.borderWidth,
            strokeStyle: dataset.borderColor,
            pointStyle: dataset.pointStyle,

            // Below is extra data used for toggling the datasets
            datasetIndex: i
          };
        }, this) : [];
      }
    }
 ...