Hydrostatic
Hydrostatic

Reputation: 45

When I convert canvas to png, sometimes the image is full with black

I use toDataUrl to convert canvas to png, but sometimes the image is all black and with nothing else. Miraculously, there are times when the image displays the contents of the canvas normally. Does anyone know why?

Here is my code:

// "stage" is the class name of canvas
const canvas = document.querySelector('.stage');
const image = canvas.toDataUrl('image/png');
const link = document.createElement('a');
link.href = image;
link.download = 'balabala.png';
const event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);

Upvotes: 0

Views: 1116

Answers (1)

Kresimir
Kresimir

Reputation: 797

One possibility is that the background of the canvas is transparent. Transparent PNGs in some editors (like MS Paint) appear with a black background. To remedy that, before drawing onto a canvas, fill it with a background colour:

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

So, if you're drawing with black on a transparent background, the image might appear completely black in some circumstances.

There might be other causes for this issue, of course, but this is one of them.

Upvotes: 1

Related Questions