Search code examples
javascripthtmlcanvasbase64png

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.


Solution

  • This blackening occurs because the 'image/jpeg' conversion involves setting the alpha of all canvas pixels to fully opaque (alpha=255). The problem is that transparent canvas pixels are colored fully-black-but-transparent. So when you turn these black pixels opaque, the result is a blackened jpeg.

    The workaround is to manually change all non-opaque canvas pixels to your desired white color instead of black.

    That way when they are made opaque they will appear as white instead of black pixels.

    Here's how:

    // change non-opaque pixels to white
    var imgData=ctx.getImageData(0,0,canvas.width,canvas.height);
    var data=imgData.data;
    for(var i=0;i<data.length;i+=4){
        if(data[i+3]<255){
            data[i]=255;
            data[i+1]=255;
            data[i+2]=255;
            data[i+3]=255;
        }
    }
    ctx.putImageData(imgData,0,0);