I am trying to generate a url for the canvas. Here are the steps I followed:
var can = document.getElementsByTagName("canvas"); var src = can.toDataURL("image/png");
When I tried running the above code on firebug it throws an error :
TypeError: can.toDataURL is not a function
I am running firefox 8 on ubuntu.
toDataURL() method returns a data URL containing a representation of the image in the format specified by the type parameter. The desired file format and image quality may be specified. If the file format is not specified, or if the given format is not supported, then the data will be exported as image/png .
toDataURL is a synchronous operation that does not trigger any events. Being synchronous, it's a blocking operation so no alert is required to prevent the next command from executing before toDataURL is fully complete. The next command will execute when toDataURL is fully complete.
Here is the code to do that: var canvas = document. getElementById("ex1"); var dataUrl = canvas. toDataURL(); window.
To get the image data URL of the canvas, we can use the toDataURL() method of the canvas object which converts the canvas drawing into a 64 bit encoded PNG URL. If you'd like for the image data URL to be in the jpeg format, you can pass image/jpeg as the first argument in the toDataURL() method.
getElementsByTagName
returns a NodeList
[docs], not a single element.
Simply access the first element of the list:
var src = can[0].toDataURL("image/png");
If you want to get the data URL for each canvas, then you have to iterate over the list. Otherwise, giving the canvas an ID and retrieving the reference with getElementById
might be more convenient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With