0
votes

I need to export my chart created in canvas as image file. I managed to do it but the image is transparent (no background). My question is, is there a way with code to add background color to existing image i got from canvas?

Example:

Canvas in browser: enter image description here

Canvas when exported as .png:

enter image description here

2
add a background color to your canvas? - cmorrissey
How do you export the image ? Any sample code which could be tested ? - Rayon
Have you tried to fillRect with white color your canvas before drawing the chart ? - bviale
at cmmorrissey tried this, it doesnt work? at Rayonhttps://www.youtube.com/watch?v=wokNS9EdKbA at bviale canvas overrides any fillRect effects - MapleSyrup

2 Answers

2
votes

You have several ways to accomplish your task.

By far the easiest is to fill the entire canvas with a background color before starting to draw your chart. Hint: you don't show code, but do this easy solution if possible. ;=)

context.fillStyle='white';
context.fillRect(0,0,canvas.width,canvas.height)

If you can't fill-before-starting, you still have some options.

You can save the chart to another canvas, fill the entire main canvas with background color and then redraw the saved chart back onto the main canvas.

// create a second canvas and draw the chart onto it
var secondCanvas=document.createElement('canvas');
var cctx=secondCanvas.getContext('2d');
secondCanvas.width=canvas.width;
secondCanvas.height=canvas.height;
cctx.drawImage(mainCanvas,0,0);

// fill the main canvas with a background
context.fillStyle='white';
context.fillRect(0,0,canvas.width,canvas.height)

// redraw the saved chart back to the main canvas
context.drawImage(secondCanvas,0,0);

You can use compositing to cause new drawings to be drawn behind existing pixels. The draw the entire background and it will appear behind the existing chart.

// set compositing to draw all new pixels (background) UNDER
// the existing chart pixels
context.globalCompositeOperation='destination-over';

// fill the main canvas with a background
context.fillStyle='white';
context.fillRect(0,0,canvas.width,canvas.height)

// always clean up ... reset compositing to default
context.globalCompositeOperation='source-over';
-1
votes

There is no need to use JavaScript, just give the image a background color using CSS.

<style>
    img {
        background-color: black;
    }
</style>
<img src="...">

See this JSFiddle for another example: https://jsfiddle.net/3jch7z94/1/