Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change html canvas black background to white background when creating jpg image from png image

I have a canvas which is loaded with a png image. I get its jpg base64 string by .toDataURL() method like this:

 $('#base64str').val(canvas.toDataURL("image/jpeg"));

But the transparent parts of the png image are shown black in the new jpg image.

Any solutions to change this color to white? Thanks in advance.

like image 784
Payam Sh Avatar asked Aug 22 '15 19:08

Payam Sh


People also ask

How do I remove a black background from a PNG image?

When a PNG image with a transparent background is selected from the Recent FIle selector and appears with a black background, the black background can be removed by re-uploading the image as a New File each time you use the image.

How do you make a JPG background transparent?

You can create a transparent area in most pictures. Select the picture that you want to create transparent areas in. Click Picture Tools > Recolor > Set Transparent Color.

Can PNG have white background?

A PNG is an image file type that allows you to have no background color. Most images cover a certain number of pixels and have color in all of those pixels, even if that color is white.


1 Answers

After spending a lot of time on this and this post specifically, and these solutions kinda worked expect I just couldn't get the canvas to look right. Anyway I found this solution elsewhere and wanted to post it here incase it helps someone else from spending hours trying to get the black background to white and look like the original.

public getURI(): string {
    let canvas = <HTMLCanvasElement>document.getElementById('chartcanvas');
    var newCanvas = <HTMLCanvasElement>canvas.cloneNode(true);
    var ctx = newCanvas.getContext('2d');
    ctx.fillStyle = "#FFF";
    ctx.fillRect(0, 0, newCanvas.width, newCanvas.height);
    ctx.drawImage(canvas, 0, 0);
    return newCanvas.toDataURL("image/jpeg");
}
like image 72
TJ972 Avatar answered Oct 23 '22 11:10

TJ972