views:

1541

answers:

2

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.

+2  A: 

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.

Fabien Ménager
Thanks, that sounds like what I need. I'd appreciate the optimized version. You should be able to find my email address by visiting my website listed in my profile.
Doug
No problem !http://flotr.googlecode.com/svn/trunk/flotr/flotr/prototype/lib/canvas2image.jsI changed the BMP render to have an alpha channel, and a few speed optimizations. In fact I used in a free library I'm working on, so it is free, and will always be.
Fabien Ménager
Thanks, much! The project I'm planning will likely have the source freely available since it'll mostly be for personal use.
Doug
Is there any way to get a Save As... dialog in Chrome as for Firefox with Canvas2Image?
Sam Dutton
canvas2image, is it worked in the IE? If yes then can you please send me the files.
Suvonkar
+1  A: 

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.

Matthew Crumley