user2293897
user2293897

Reputation: 23

HTML5 canvas toDataURL sometimes returns "data:," instead of the image

I have created a canvas with document.createElement("canvas"):

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

Then I use canvas.toDataURL() to get its base64 string:

var str = canvas.toDataURL();

but the 'str' sometimes returns as "data:,", with no image data in it. Just those six chars.

Sometimes it returns the correct string like "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAEGgAABPsCAYAAABg/aH3AAAgAElEQVR4XuzcQREAAAjDM..."

I the canvas.width is too large ....

Upvotes: 2

Views: 2673

Answers (1)

nfroidure
nfroidure

Reputation: 1601

You should try to create a 2D context explicitly and then draw in it an empty shape, something like:

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

Edit: It seems that your canvas contains too much data to be exported as a 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:,"

Upvotes: 2

Related Questions