admin管理员组

文章数量:1297082

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

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

Share Improve this question asked May 27, 2009 at 17:05 DougDoug 1,0931 gold badge10 silver badges16 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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.

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.

本文标签: javascriptGenerate image data from HTML Canvas elementStack Overflow