Is it possible to capture or print what's displayed in an html canvas as an image or pdf?
I'd like to generate an image via canvas, and be able to generate a png from that image.
Is it possible to capture or print what's displayed in an html canvas as an image or pdf?
I'd like to generate an image via canvas, and be able to generate a png from that image.
If you are using jQuery, which quite a lot of people do, then you would implement the accepted answer like so:
Oops. Original answer was specific to a similar question. This has been revised:
with the value in IMG you can write it out as a new Image like so:
Another interesting solution is PhantomJS. It's a headless WebKit scriptable with JavaScript or CoffeeScript.
One of the use case is screen capture : you can programmatically capture web contents, including SVG and Canvas and/or Create web site screenshots with thumbnail preview.
The best entry point is the screen capture wiki page.
Here is a good example for polar clock (from RaphaelJS):
Do you want to render a page to a PDF ?
On some versions of Chrome, you can:
ctx.drawImage(image1, 0, 0, w, h);
I would use "wkhtmltopdf". It just work great. It uses webkit engine (used in Chrome, Safari, etc.), and it is very easy to use:
That's it!
Try it
I thought I'd extend the scope of this question a bit, with some useful tidbits on the matter.
In order to get the canvas as an image, you should do the following:
You can use this to write the image to the page:
Where "image/png" is a mime type (png is the only one that must be supported). If you would like an array of the supported types you can do something along the lines of this:
You only need to run this once per page - it should never change through a page's lifecycle.
If you wish to make the user download the file as it is saved you can do the following:
If you're using that with different mime types, be sure to change both instances of image/png, but not the image/octet-stream. It is also worth mentioning that if you use any cross-domain resources in rendering your canvas, you will encounter a security error when you try to use the toDataUrl method.