2

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 ....

Laurel
  • 5,965
  • 14
  • 31
  • 57

1 Answers1

2

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:,"
Laurel
  • 5,965
  • 14
  • 31
  • 57
nfroidure
  • 1,531
  • 12
  • 20
  • I have tried your method,and sadly it has no effect...what made me confusional is that, **sometimes wrong but sometimes correct**. I am new to html..in which situation does the canvas.toDataURL() returns **"data:,"** ? – user2293897 Apr 18 '13 at 08:30
  • I assume that when the image is empty, it can happen, but, i'll have to know in wich browser you got this issue. I tested on Chrome & Firefox and it never happenned. – nfroidure Apr 18 '13 at 11:27
  • I seems that you're canvas is too large, i tried this : var canvas = document.createElement("canvas"); canvas.width = 400000000; canvas.height = 500000000; var ctx=canvas.getContext('2d'); ctx.fillRect(0,0,0,0); canvas.toDataURL(); And i had the same result : data:; In Google Chrome It must be a limitation due to the maximum size of a dataUri. – nfroidure Apr 18 '13 at 11:28