tags:

views:

5146

answers:

4

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 I'd like to be able to generate a png from that image.

+1  A: 

http://ajaxian.com/archives/canvas2image-save-out-your-canvas-data-to-images

Hope that helps.

Edit: here's the original site for Canvas2Image http://www.nihilogic.dk/labs/canvas2image/

Jonathan Fingland
That's great, you can always do a screenshot if you don't need to do it programmatically too.
Matthew James Taylor
true, but he didn't specify whether it was for personal use or for sending to a server. Might need a little tweaking to accomplish the second task though.
Jonathan Fingland
I am looking for programmatic, not screen capture.
Parand
I'm not sure what the license terms are on Canvas2Image but you might want to take the generated image and post it to the server (skipping the save/output to browser step). From the examples, I gather that's not how it was intended to be used.
Jonathan Fingland
/* * Canvas2Image v0.1 * Copyright (c) 2008 Jacob Seidelin, [email protected] * MIT License [http://www.opensource.org/licenses/mit-license.php] */You can do what you want with it. I made an optimized version of this lib here : http://flotr.googlecode.com/svn/trunk/flotr/flotr/prototype/lib/canvas2image.js
Fabien Ménager
wow. so you're one of the developers for flotr? I use it on a page http://pq.ashita.org/bandannaguide.php thanks to you and the team. much appreciated
Jonathan Fingland
+8  A: 

HTML5 provides Canvas.toDataURL(mimetype), which is implemented in Opera, Firefox, and Safari 4 beta. There are a number of security restrictions however (mostly to do with drawing content from another origin onto the canvas).

So you don't need an additional library, eg.

 <canvas id=canvas width=200 height=200></canvas>
 <script>
      window.onload = function() {
          var canvas = document.getElementById("canvas");
          var context = canvas.getContext("2d");
          context.fillStyle = "green";
          context.fillRect(50, 50, 100, 100);
          // no argument defaults to image/png; image/jpeg, etc also work on some
          // implementations -- image/png is the only one that must be supported per spec.
          window.location = canvas.toDataURL("image/png");
      }
 </script>

Theoretically this should create and then navigate to an image with a green square in the middle of it, but i haven't tested.

olliej
+3  A: 

Oops. Original answer was specific to a similar question. This has been revised:

var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");
var img     = canvas.toDataURL("image/png");

with the value in IMG you can write it out as a new Image like so:

document.write('<img src="'+img+'"/>');
michael
Thanks michael, looks like getContext together with toDataURL would do it
Parand