Learn why your exported canvas image have black background and how to solve it !

Image created from canvas have black background (HTML5)

Does your exported image from a canvas element a black background with toDataURL() method ? Really annoying problem isn't?.

The HTMLCanvasElement.toDataURL() method returns a data URIs containing a representation of the image in the format specified by the type parameter (defaults to PNG).

The black background of an image is caused by the incorrect exportation format, if you have this problem, you're probably exporting the image in this way :

var Image = canvas.toDataURL("image/jpeg");

Normally, you ommit the first parameter (The format) as it will be always PNG, but if you specify explicitly the format and your image has transparency, you'll face this problem.

To solve this error, change (or ommit) the first parameter from image/jpeg to image/png.

var Image = canvas.toDataURL("image/png");
// Or without parameter because the default exporting format is PNG
var Image = canvas.toDataURL();

Why the image needs to be exported in PNG format?

Simply because if your canvas have transparent background, and your exported format is JPG , will be impossible to generate the transparency to the JPG format because only the PNG format supports transparency.


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors