Search code examples
javascripthtmlimagecanvaskineticjs

Kineticjs export to jpeg fill transparent pixel with white?


I want to export my Kineticjs stage with:

stage.toDataURL({
  mimeType : "image/jpeg",
  callback : function() {}
}); 

When I export this:

enter image description here

I get the following image after export:

enter image description here

All the transparent pixels are set to black.

How can I set all the transparent pixel to white before exporting?


Solution

  • The Problem

    This occurs because on the KineticJS stage, the background is transparent: rgba(0,0,0,0).

    The last zero in rgba is the alpha==the opacity.

    But jpeg doesn't allow different opacities. It only allows solid colors.

    So when you save the stage with toDataURL, jpeg will make the background opacity a solid color == rgba(0,0,0,1).

    rgba(0,0,0,1) is black.  
    

    Therefore, transparent pixels are always written as black when saving a jpeg.

    The solution

    Add a background rectangle that fills the stage with white (or other color) so jpeg will know which color to use for the background pixels.

    A Demo: http://jsfiddle.net/m1erickson/WZ5G2/