Chartjs-Add dynamically function to Chart.js

0👍

The function does work but you are missing config, in V3 by default linecharts dont fill anymore so you will need to set fill to true, also the dataset background property overrides the one set in the elements part so you will need to rename backgroundColor to pointBackgroundColor if you want the points to have that color, then it works fine:

var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
  type: "line",
  data: {
    labels: [
      "Sunday",
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday"
    ],
    datasets: [{
        data: [86, 114, 106, 106, 107, 111, 133],
        label: "Total",
        borderColor: "rgb(62,149,205)",
        pointBackgroundColor: "rgb(62,149,205,0.1)",
        fill: true
      },
      {
        data: [70, 90, 44, 60, 83, 90, 100],
        label: "Accepted",
        borderColor: "rgb(60,186,159)",
        pointBackgroundColor: "rgb(60,186,159,0.1)",
        fill: true
      },
      {
        data: [10, 21, 60, 44, 17, 21, 17],
        label: "Pending",
        borderColor: "rgb(255,165,0)",
        pointBackgroundColor: "rgb(255,165,0,0.1)",
        fill: true
      },
      {
        data: [6, 3, 2, 2, 7, 0, 16],
        label: "Rejected",
        borderColor: "rgb(196,88,80)",
        pointBackgroundColor: "rgb(196,88,80,0.1)",
        fill: true
      }
    ]
  },
});

myChart.data.labels.push('June');

myChart.options.plugins.legend.onClick = function(e, legendItem, legend) {
  console.log('legend click');
  console.log(legendItem);
};

myChart.options.elements.line.backgroundColor = function(ctx) {
  return '#000000';
};

myChart.update();
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.min.js"></script>
<canvas id="myChart" width="500" height="150"></canvas>

Leave a comment