ChartjsNodeCanvas icon indicating copy to clipboard operation
ChartjsNodeCanvas copied to clipboard

backgroundColour not applied to full height of image with devicePixelRatio: 2

Open smarr opened this issue 2 years ago • 1 comments

When setting the backgroundColour and devicePixelRatio: 2, the background color is applied to the correct width, but not the full hight.

I assume that the issue is that the hight is the one not scaled to the 2x ratio.

const canvasOptions: ChartJSNodeCanvasOptions = {
    width,
    height,
    backgroundColour: '#f00'
}

const chartJSNodeCanvas = new ChartJSNodeCanvas(canvasOptions);

const configuration = {
  // ...
  options: {
    devicePixelRatio: 2,
  }
};

chartJSNodeCanvas.renderToBuffer(configuration);

Versions

  • Chart.JS version: 3.9.1
  • chartj-node-canvas version: 4.1.6

I currently work around this by using the following chartCallback:

  const canvasOptions: ChartJSNodeCanvasOptions = {
    width,
    height,
    backgroundColour,
    chartCallback: (ChartJS) => {
      ChartJS.register({
        id: 'my_background_color',
        beforeDraw: (chart, _options) => {
          const ctx = chart.ctx;
          ctx.save();
          ctx.fillStyle = backgroundColour;
          ctx.fillRect(0, 0, width, chart.height);  // <- note the `chart.height` here, which gives the correct result. I am not sure why just `width` works though. It's a bit odd.
          ctx.restore();
        }
      });
    }
  };

smarr avatar May 01 '23 14:05 smarr

And just for good measures: workaround based on https://github.com/SeanSobey/ChartjsNodeCanvas/issues/7#issuecomment-605677826

smarr avatar May 01 '23 19:05 smarr