Javascript 当我将画布转换为png时,有时图像充满了黑色

Javascript 当我将画布转换为png时,有时图像充满了黑色,javascript,canvas,Javascript,Canvas,我使用toDataUrl将画布转换为png,但有时图像全是黑色,没有其他内容。神奇的是,有时图像会正常显示画布的内容。有人知道为什么吗 这是我的密码: // "stage" is the class name of canvas const canvas = document.querySelector('.stage'); const image = canvas.toDataUrl('image/png'); const link = document.createElement('a');

我使用toDataUrl将画布转换为png,但有时图像全是黑色,没有其他内容。神奇的是,有时图像会正常显示画布的内容。有人知道为什么吗

这是我的密码:

// "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);

一种可能性是画布的背景是透明的。某些编辑器(如MS Paint)中的透明PNG显示为黑色背景。要解决此问题,在画布上绘制之前,请使用背景色填充:

context.fillStyle = "white";
context.fillRect(0, 0, canvas.width, canvas.height);
因此,如果在透明背景上使用黑色绘制,在某些情况下,图像可能会显示为完全黑色


当然,这个问题可能还有其他原因,但这是其中之一

这可能是因为您经常使用setTimeout刷新画布,而在您尝试保存画布时,它没有机会绘制所有内容吗?听起来在调用此脚本时,似乎没有绘制任何内容。你能告诉我怎么叫它和绘图部分吗?即使是瞎拍,我也会说你在画图之前要等待图像的加载,而不是导出。@kaido当我使用“toDataUrl”时,画布已经绘制出来了。如何绘制呢?为了帮助你,我们需要看一下。它是二维上下文、webgl上下文还是已在此画布上初始化的位图渲染器?