What is the best way to generate image data from the contents of an HTML canvas element?
I'd like to create the image data such that it can be transmitted to a server (it's not necessary for the user to be able to directly save to a file). The image data should be in a common format such as PNG or JPEG.
Solutions that work correctly in multiple browsers are preferred, but if every solution depends on the browser, recent versions of Firefox should be targeted.
I think a lib you can use is Canvas2Image, it uses native features from Canvas, but it won't work on any browser. I have an optimized version of this lib, if you want to, I'll share it with you.
Then you could get the generated Data URI and send it using Ajax to the server.
Firefox and Opera have a
toDataURL()
method that returns a data-URL formatted PNG. You can assign the result to a form field to submit it to the server.The data URL is base-64 encoded, so you will have to decode it on the server side. You would also need to strip off the "data:image/png;" part of course.