[Chartjs]-Horizontal gradient for every single bar in group chart js

1๐Ÿ‘

โœ…

You will need to use a scriptable function in which you pass the correct start and end x values:

window.onload = function() {
  var ctx = document.getElementById("canvas").getContext("2d");

  window.myBar = new Chart(ctx, {
    type: "bar",
    data: {
      labels: [
        ["๐‰๐˜๐’๐„๐‹๐„๐‚๐€", "๐Ÿ๐ŸŽ๐ŸŽ ๐ฆ๐  + ๐Œ๐“๐—", "(n = 475)"],
        ["๐€๐๐š๐ฅ๐ข๐ฆ๐ฎ๐ฆ๐š๐›", "+ ๐Œ๐“๐—", "(n = 325)"],
        ["๐๐ฅ๐š๐œ๐ž๐›๐จ", "+ ๐Œ๐“๐—", "(n = 475)"]
      ],
      datasets: [{
          label: "American Express",
          backgroundColor: (context) => {
            if (!context.element.x || !context.element.width) {
              return
            }

            const {
              ctx
            } = context.chart;

            const {
              x,
              width
            } = context.element;

            const background_1 = ctx.createLinearGradient(x - (width / 2), 0, x + (width / 2), 0);

            background_1.addColorStop(0, '#005AB1');
            background_1.addColorStop(0.35, '#4F8ED0');
            background_1.addColorStop(0.55, '#BED0F9');
            background_1.addColorStop(0.70, '#AEC9EF');
            background_1.addColorStop(1, '#0069B9');

            return background_1;
          },
          borderColor: "#005AB1",
          borderWidth: 1,
          borderRadius: 15,
          data: [77, 66, 81]

        },
        {
          label: "Mastercard",
          backgroundColor: "#DDD2BC",
          borderColor: "#DDD2BC",
          borderWidth: 1,
          borderRadius: 15,
          data: [71, 31, 78]
        },
        {
          label: "Paypal",
          backgroundColor: "#C1C1C0",
          borderColor: "#C1C1C0",
          borderWidth: 1,
          borderRadius: 15,
          data: [50, 38, 71]
        }
      ]
    },
    options: {
      responsive: true,
      plugins: {
        legend: {
          position: "top"
        },
        title: {
          display: true,
          text: "Chart.js Bar Chart"
        }
      }
    },
  });
};
<!DOCTYPE html>
<html lang="en" class="no-js">

<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
</head>

<body>

  <div id="container" style="width: 100%;">
    <canvas id="canvas"></canvas>
  </div>

  <!-- script -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</body>

</html>

Leave a comment