Rectangle 27 1

Browsers may happily ignore any quality parameter given for the toDataUrl and such. I don't believe honoring it is mandatory by the specification.

The only way to control the quality exactly would be

Alternative you may try canvas.mozGetAsFile() / canvas.toBlob(), but I'll believe browsers still won't honour quality parameters.

HTML5 Canvas toDataURL 8 bit? - Stack Overflow

html5-canvas
Rectangle 27 7

base64_decode

If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

<?php
  $encodedData = str_replace(' ','+',$encodedData);
  $decocedData = base64_decode($encodedData);
?>

php - html5 canvas toDataURL returns blank image - Stack Overflow

php javascript html5 canvas data-url
Rectangle 27 7

Create a new Canvas object of a specific size, use drawImage to copy a specific part of your canvas to a specific area of the new one, and use toDataURL() on the new canvas.

oh have got to love the simple answers i did not even think of that. Will test now then update

Gunna need a minute its throwing an error when i try to do that sec err 18 when i try to do todataurl the second time

Capturing only a portion of canvas with .todataurl Javascript/HTML5 - ...

javascript html5 canvas
Rectangle 27 2

You are first calling loadImages, then getting the data URL right after that loadImages call. However, as your loadImages implementation shows, calling it merely starts the loading process; the callback is called when all images have been loaded, which is some time in the future.

Currently you're getting a blank image because the images have not been loaded yet, so your callback is not called yet, and as a result your canvas is still empty.

In short, everything that relies on the images having being loaded (e.g. your expected toDataURL result) should be executed when those images are actually loaded - thus in the callback.

loadImages(sources, function(images) {
  context.drawImage(images.darthVader, 250, 30, 250, 250);
  context.drawImage(images.yoda, 530, 30, 250, 250);

  var dataURL = canvas.toDataURL();
  document.getElementById("canvasImg").src = dataURL;
});

nothing happens when i add this into the callback. not even the src is set to DataURL

@Badal Surana: Are the images painted on the canvas? Any errors in the console?

There's an error in the console. You're drawing images from other websites, and as a security measure you cannot get the data URL. You could host the images on your own domain instead.

javascript - html5 canvas toDataURL returns blank image - Stack Overfl...

javascript html5 html5-canvas
Rectangle 27 27

You must set the CORS request before the src - just swap the lines into:

img.crossOrigin = "Anonymous";
img.src = document.getElementById("imgbox").value;

You will also need to add an onload handler to the image as loading is asynchronous:

img.onload = function() {
    context.drawImage(this, 40, 40);
    // call next step in your code here, f.ex: nextStep();
};
img.crossOrigin = "Anonymous";
img.src = document.getElementById("imgbox").value;

Wait, now it only works with some images. Images from imgur work but some random images from google image search still won't draw to the canvas. For example, icons.iconarchive.com/icons/yellowicon/game-stars/256/ won't get drawn at all. Any idea why?

@Joey you can only request CORS usage, the server may refuse the request which will make the image loading fail. You need to check which servers allow and which doesn't. For those who won't allow CORS use just remove the request (crossOrigin line). For images that you can't load using CORS request you need to copy them to your own server (same as page) or move them to another server which allow cors use. (hope that made sense)

Ugh, alight. Suppose I convert the image to a base64 string and then create a new image using that as the data URL? Can the client enable cors for that new image?

I don't quite understand. If I programmatically (using javascript) generated a base64 string that, if converted to a png image would just be random pixels, can I write that to the canvas without getting a cors error?

javascript - Drawing images to canvas with img.crossOrigin = "Anonymou...

javascript html5 canvas cors todataurl
Rectangle 27 9

widthOfImage * heightOfImage * 4
var imageDataArrayLenth = 100 * 100 * 4 = 40 000 (bytes);
  • BLOB (JPG or PNG) is imageData compressed with jpg or png algorithm can be less sized by 10 or 20 times than imageData (depends on image content).
  • DataURL (BASE64) is imageData compressed to JPG or PNG, then converted to string, and this string is larger by 37% (info) than BLOB.
//Example of using blob with objectURL
var canvas = document.getElementById("canvas");

canvas.toBlob(function(blob) {
  var newImg = document.createElement("img"),
      url = URL.createObjectURL(blob);

  newImg.onload = function() {
    // no longer need to read the blob so it's revoked
    URL.revokeObjectURL(url);
  };

  newImg.src = url;
  document.body.appendChild(newImg);
});

javascript - Result of html5 Canvas getImageData or toDataURL - Which ...

javascript html5 canvas
Rectangle 27 9

widthOfImage * heightOfImage * 4
var imageDataArrayLenth = 100 * 100 * 4 = 40 000 (bytes);
  • BLOB (JPG or PNG) is imageData compressed with jpg or png algorithm can be less sized by 10 or 20 times than imageData (depends on image content).
  • DataURL (BASE64) is imageData compressed to JPG or PNG, then converted to string, and this string is larger by 37% (info) than BLOB.
//Example of using blob with objectURL
var canvas = document.getElementById("canvas");

canvas.toBlob(function(blob) {
  var newImg = document.createElement("img"),
      url = URL.createObjectURL(blob);

  newImg.onload = function() {
    // no longer need to read the blob so it's revoked
    URL.revokeObjectURL(url);
  };

  newImg.src = url;
  document.body.appendChild(newImg);
});

javascript - Result of html5 Canvas getImageData or toDataURL - Which ...

javascript html5 canvas
Rectangle 27 1

I just went through this the other day... the getImageData method returns an image object where the actual data is stored in a uint8array... you have to get the data converted to something your database can manage and its just not worth it, the final output is much larger than the toDataURL method

Its also very simple to get toDataURL base64 string back onto the canvas... you just instantiate a new image and give the src the base64 string

javascript - Result of html5 Canvas getImageData or toDataURL - Which ...

javascript html5 canvas
Rectangle 27 1

I just went through this the other day... the getImageData method returns an image object where the actual data is stored in a uint8array... you have to get the data converted to something your database can manage and its just not worth it, the final output is much larger than the toDataURL method

Its also very simple to get toDataURL base64 string back onto the canvas... you just instantiate a new image and give the src the base64 string

javascript - Result of html5 Canvas getImageData or toDataURL - Which ...

javascript html5 canvas
Rectangle 27 6

Good question! I'm not sure about the true sizes of the objects themselves, and it should differ between implementions of JS, but that doesn't mean we can't make some educated guesses.

First we can use the approximation function from this question: JavaScript object size

The string is perhaps 80116 bytes, compared to the ImageData's 720056 bytes. Or thereabouts.

There's an order of magnitude difference here, and the difference would be even more stark if the image was simple. It's worth remembering that the Base64 representation can be compressed (and it is). Let's take it to the limit for a moment to see, by using a blank canvas:

On a blank canvas the dataURL string is just 1996 bytes (or thereabouts) but the image data, which of course still dutifully describes every single pixel in painstaking array detail, is still 720056.

In short, if you're storing it, the base64 string probably takes up less space. By an order of magnitude.

The tradeoff is the usual - for the massive amount of storage, you gain tons of processing time. I just had a project where I was caching a single (roughly 600x500) image. I did it first with toDataURL, and it was small - but setting new Image().src to the URL string dropped my framerate by a third. In my case, it was worth the memory to improve the speed.

javascript - Result of html5 Canvas getImageData or toDataURL - Which ...

javascript html5 canvas
Rectangle 27 6

Good question! I'm not sure about the true sizes of the objects themselves, and it should differ between implementions of JS, but that doesn't mean we can't make some educated guesses.

First we can use the approximation function from this question: JavaScript object size

The string is perhaps 80116 bytes, compared to the ImageData's 720056 bytes. Or thereabouts.

There's an order of magnitude difference here, and the difference would be even more stark if the image was simple. It's worth remembering that the Base64 representation can be compressed (and it is). Let's take it to the limit for a moment to see, by using a blank canvas:

On a blank canvas the dataURL string is just 1996 bytes (or thereabouts) but the image data, which of course still dutifully describes every single pixel in painstaking array detail, is still 720056.

In short, if you're storing it, the base64 string probably takes up less space. By an order of magnitude.

The tradeoff is the usual - for the massive amount of storage, you gain tons of processing time. I just had a project where I was caching a single (roughly 600x500) image. I did it first with toDataURL, and it was small - but setting new Image().src to the URL string dropped my framerate by a third. In my case, it was worth the memory to improve the speed.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - Result of html5 Canvas getImageData or toDataURL - Which ...

javascript html5 canvas
Rectangle 27 1

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

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:,"

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:," ?

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.

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.

javascript - HTML5 canvas toDataURL sometimes returns "data:," instead...

javascript html html5-canvas
Rectangle 27 2

Here's a method that uses an off-screen canvas:

var canvas = document.createElement('canvas');
canvas.width = desiredWidth;
canvas.height = desiredHeight;
canvas.getContext('2d').drawImage(originalCanvas,x,y,w,h,0,0,desiredWidth, desiredHeight);
result = canvas.toDataURL()

Capturing only a portion of canvas with .todataurl Javascript/HTML5 - ...

javascript html5 canvas
Rectangle 27 1

When the server requires authorization to access the images the value should be:

img.crossOrigin = "Use-Credentials";

javascript - Drawing images to canvas with img.crossOrigin = "Anonymou...

javascript html5 canvas cors todataurl
Rectangle 27 4

Note there is a situation when working with an HTML5 canvas that is worth noting. Getting the canvas data as a DataURI string and sending that to server can cause this error. Canvas .toDataURL() will give something like "data:image/png;base64,iVBORw0KGg..." which you can send to server with other information, so its different than a standard multi-part form upload. On the server side if you just set this to the paperclip attachment field you will get this error. You need to conver it to a file or IO object. You could write a temp file like this:

data_uri = params[:canvasDataUri]
encoded_image = data_uri.split(",")[1]
decoded_image = Base64.decode64(encoded_image)
File.open("signature.png", "wb") { |f| f.write(decoded_image) }

or use Ruby's StringIO which acts like an in memory file interface

@docHolder.document = StringIO.new(decoded_image)
StringIO(<your_file_string_representation>)

ruby on rails - Paperclip exception : Paperclip::AdapterRegistry::NoHa...

ruby-on-rails paperclip
Rectangle 27 4

Note there is a situation when working with an HTML5 canvas that is worth noting. Getting the canvas data as a DataURI string and sending that to server can cause this error. Canvas .toDataURL() will give something like "data:image/png;base64,iVBORw0KGg..." which you can send to server with other information, so its different than a standard multi-part form upload. On the server side if you just set this to the paperclip attachment field you will get this error. You need to conver it to a file or IO object. You could write a temp file like this:

data_uri = params[:canvasDataUri]
encoded_image = data_uri.split(",")[1]
decoded_image = Base64.decode64(encoded_image)
File.open("signature.png", "wb") { |f| f.write(decoded_image) }

or use Ruby's StringIO which acts like an in memory file interface

@docHolder.document = StringIO.new(decoded_image)
StringIO(<your_file_string_representation>)

ruby on rails - Paperclip exception : Paperclip::AdapterRegistry::NoHa...

ruby-on-rails paperclip
Rectangle 27 3

Note there is a situation when working with an HTML5 canvas that is worth noting. Getting the canvas data as a DataURI string and sending that to server can cause this error. Canvas .toDataURL() will give something like "data:image/png;base64,iVBORw0KGg..." which you can send to server with other information, so its different than a standard multi-part form upload. On the server side if you just set this to the paperclip attachment field you will get this error. You need to conver it to a file or IO object. You could write a temp file like this:

data_uri = params[:canvasDataUri]
encoded_image = data_uri.split(",")[1]
decoded_image = Base64.decode64(encoded_image)
File.open("signature.png", "wb") { |f| f.write(decoded_image) }

or use Ruby's StringIO which acts like an in memory file interface

@docHolder.document = StringIO.new(decoded_image)
StringIO(<your_file_string_representation>)

ruby on rails - Paperclip exception : Paperclip::AdapterRegistry::NoHa...

ruby-on-rails paperclip
Rectangle 27 0

But- that needs an ID right?

It doesn't need an ID, but an ID won't hurt (so long as it's actually unique ;-)). Any method to select a DOM element will work here. If there's only one canvas on the page, this would suffice, for example:

When I created the canvas in the createCanvas function, how would I make an id accompanying it?

You'd just set the ID property of the canvas element before returning it. Remember, you need to ensure that this value is unique!

That's true. I didn't notice that the canvases is appended to a <div id="canvas">.

I would pefer an ID though. Yes, I know about getElementsByTagName...

OH I just saw the rest of your answer. :) SO cool! :) Didn't know you could just change the id with canvas.node.id! :) Amazing! :) It does make sense though, its just like canvas.node.style or canvas.node.value or something. dumb moment for me! :) Thanks so much!

javascript - HTML5 canvas, save as image, toDataURL(), create ID - Sta...

javascript html5 canvas
Rectangle 27 0

For updating the spinner, try to modify the code so that an extra update event is created.

You can do this by using setTimeout:

There is also an error in the code that does probably not affect anything but it doesn't hurt to get it right -

The argument for toDataURL must be an image type only, ie. image/png, image/jpeg, image/webp etc. The base64 part should not be there (probably came along when you copied the image type from an exisiting data-uri). As PNG is default there is no need to specify it in any case - simply use:

would a check to .complete be betten than hardcoding the arbitrary 100ms value?

html - HTML5 Canvas toDataURL() blocks JavaScript Call? - Stack Overfl...

javascript html html5 canvas
Rectangle 27 0

maximum size for decoded GIF, PNG, and TIFF

  • The maximum size for a canvas element is 3 megapixels for devices with less than 256 MB RAM and 5 megapixels for devices with greater or equal than 256 MB RAM.

This limits don't throw any errors, so then you will try to render or read 6MB image you will get a broken blob/dataURL string and so on. And you will think that File API is broken, canvas methods toDataURL/toBlob are broken, and you will be right. But bugs aren't in browser, this is a system limitation.

So this limitations create a broken behavior for javascript API.

javascript - iOS HTML5 Canvas toDataURL - Stack Overflow

javascript ios html5 canvas