Search code examples
javascriptbackgroundgradient

chart.js gradient background problems with browser zoom


I have a gradient in my chart.js as background. This works well if my screen zoom is set to 100%

If I change my zoom ([Strg] + [+] or [-]), the gradient doesn't take this in account. What can I do?

HTML:

<div>
  <canvas id="myChart"></canvas>
</div>

JavaScript:

const labels = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
];

const data = {
  labels: labels,
  datasets: [{
    label: 'My First dataset',
    backgroundColor: 'rgb(255, 99, 132)',
    borderColor: 'rgb(255, 99, 132)',
    data: [0, 10, 5, 2, 20, 30, 45],
  }]
};

const plugin_gradient = {
  beforeDraw: function(chart, args, options) {
    const ctx = chart.ctx;
    const canvas = chart.canvas;
    const chartArea = chart.chartArea;
    var gradientBack = canvas.getContext("2d").createLinearGradient(0, canvas.height, canvas.width, 0);
    gradientBack.addColorStop(1, "rgba(255, 120, 120, 1)");
    gradientBack.addColorStop(.5, "rgba(255, 255, 120, 1)");
    gradientBack.addColorStop(0, "rgba(120, 255, 120, 1)");
    ctx.fillStyle = gradientBack;
    ctx.fillRect(chartArea.left, chartArea.bottom, chartArea.right - chartArea.left, chartArea.top - chartArea.bottom);
  }
};

const config = {
  type: 'line',
  data: data,
  plugins: [plugin_gradient],
  options: {}
};

const myChart = new Chart(
  document.getElementById('myChart'),
  config
);

Here is a JSFiddle


Solution

  • Thanks to this guy on youtube: Chart JS with "How to Create Diagonal Gradient Background in ChartArea in Chart JS" my gradient is now working for me.

    The working plugin part:

    const plugin_gradient = {
            id : "plugin_gradient",
            beforeDraw(chart, args, pluginOptions) {
                const { ctx, chartArea: { top, bottom, left, right, width, height } } = chart;
                ctx.save();
                
                const gradientColor = ctx.createLinearGradient(left, bottom, right, top);
                gradientColor.addColorStop(0, "rgba(120, 255, 120, 1)");
                gradientColor.addColorStop(.5, "rgba(255, 255, 120, 1)");
                gradientColor.addColorStop(1, "rgba(255, 120, 120, 1)");
                
                ctx.fillStyle = gradientColor;
                ctx.fillRect(left, top, width, height);
                ctx.restore ();
              }
          };
    

    A JSFiddle can be found here