1
votes

I am building some charts on a canvas using Charts.js and Bootstrap. Users want to be able to download a PNG file of the chart to copy it into a Powerpoint slide. I have the following function working and it downloads the file but it has a completely black background. On the page the image has a white background. I see a bunch of posts about this with JPEG and the solution says to use PNG but I am using PNG. Not sure if there is something I can change in the canvas itself. I have tried to explicitly set the background color of the canvas to white but that doesn't help.

the downloadToPNG function:

function downloadToPNG() {
    var canvas   = document.getElementById('parentCanvas');
    var dt = canvas.toDataURL('image/png');
    var hiddenElement = document.createElement('a');
    hiddenElement.href = dt;
    hiddenElement.target = '_blank';
    hiddenElement.download = fileName;
    hiddenElement.click();
    hiddenElement.remove();
}
1
Does the saved image itself has a black background or is it only when passed to power-point ? Is it really an background or is the whole image completely black ? What kind of context is initialized on the canvas ? How did you try to add the white background ? Could you add an minimal reproducible example ?Kaiido

1 Answers

0
votes

The background might be because of some lost cascaded CSS values, you might want to double check the background colors for html, body, and every parent element. This may also have to do with the png information being passed around as base64 encoded, which is normal method for the browser to hash image information into alphanumerics. This thread might help with that how to save canvas as png image?