首页 文章

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

提问于
浏览
0

我使用 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);

1 回答

  • 0

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

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

    因此,如果您在透明背景上使用黑色绘图,则在某些情况下图像可能会显示为黑色 .

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

相关问题