Chartjs-Chart.js – Add gradient to line chart background

1👍

backgroundColor with createLinearGradient should help here. backgroundColor propertly takes in different types of colors. You need to create a gradient and specify the same.

Have created a sample snippet for you reusing your code. Follow lines 4-7 and line 34.

const ctx = document.getElementById("myChart");

// Create gradient here
const ctxForGradient = document.getElementById('myChart').getContext('2d');
const gradientFill = ctxForGradient.createLinearGradient(0, 500, 0, 50);
gradientFill.addColorStop(0, "rgba(255, 0, 0, 0.9)");
gradientFill.addColorStop(1, "rgba(0, 0, 255, 0.9)");

var speedData = {
  labels: [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
  ],

  datasets: [{
    label: "Car Speed",
    data: [7, 9, 5, 8, 9, 7, 6, 10, 4, 5, 7, 8, 9],
    lineTension: 0,
    pointBackgroundColor: "#131921",
    pointBorderColor: "white",
    pointBorderWidth: 3,
    pointRadius: 6,
    borderColor: "white",
    backgroundColor: gradientFill // Fill gradient here
  }]
};

var chartOptions = {
  legend: {
    display: false
  }
};
new Chart(ctx, {
  type: "line",
  data: speedData,
  options: chartOptions
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<canvas id="myChart"></canvas>

Hope it helps. Revert for any doubts/clarification.

Leave a comment