HTML5 canvas toDataURL有时会返回“data:”而不是图像

时间:2013-04-18 07:31:35

标签: javascript html html5-canvas

我创建了一个带有document.createElement("canvas")的画布:

var canvas = document.createElement("canvas");
canvas.width = width;     // width = 4000 or more
canvas.height = height;   // height = 5000 or more

然后我使用canvas.toDataURL()来获取其base64字符串:

var str = canvas.toDataURL();

但'str'有时会返回"data:,",其中没有图像数据。只是那六个字符。

有时会返回正确的字符串,如"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAEGgAABPsCAYAAABg/aH3AAAgAElEQVR4XuzcQREAAAjDM..."

canvas.width太大了......

1 个答案:

答案 0 :(得分:1)

您应该尝试显式创建2D上下文,然后在其中绘制一个空形状,如:

var canvas = document.createElement("canvas");
canvas.width = 4000;
canvas.height = 5000;
var ctx=canvas.getContext('2d');
ctx.fillRect(0,0,0,0);
canvas.toDataURL();

编辑:您的画布似乎包含太多要导出为dataUri的数据:

var canvas = document.createElement("canvas");
canvas.width = 400000000;
canvas.height = 500000000;
var ctx=canvas.getContext('2d');
ctx.fillRect(0,0,0,0);
canvas.toDataURL();
// outputs : "data:,"