Wednesday, April 9th, 2008
Canvas2Image: Save out your canvas data to images
More from Jacob Seidelin. He has created Canvas2Image, a library that takes <canvas> data and makes an image out of it. This means that you can create canvas images on the fly and then:
-
-
var strDataURI = oCanvas.toDataURL();
-
// returns "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACt..."
-
See the full API in use here:
-
-
/*
-
* Canvas2Image.saveAsXXXX = function(oCanvasElement, bReturnImgElement, iWidth, iHeight) { ... }
-
*/
-
-
var oCanvas = document.getElementById("thecanvas");
-
-
Canvas2Image.saveAsPNG(oCanvas); // will prompt the user to save the image as PNG.
-
-
Canvas2Image.saveAsJPEG(oCanvas); // will prompt the user to save the image as JPEG.
-
// Only supported by Firefox.
-
-
Canvas2Image.saveAsBMP(oCanvas); // will prompt the user to save the image as BMP.
-
-
-
// returns an <img /> element containing the converted PNG image
-
var oImgPNG = Canvas2Image.saveAsPNG(oCanvas, true);
-
-
// returns an <img /> element containing the converted JPEG image (Only supported by Firefox)
-
var oImgJPEG = Canvas2Image.saveAsJPEG(oCanvas, true);
-
-
// returns an <img /> element containing the converted BMP image
-
var oImgBMP = Canvas2Image.saveAsBMP(oCanvas, true);
-
-
-
// all the functions also takes width and height arguments.
-
// These can be used to scale the resulting image:
-
-
// saves a PNG image scaled to 100x100
-
Canvas2Image.saveAsPNG(oCanvas, false, 100, 100);
-













Cool! I am going to try this with flot…
Very cool! :)
I wasted at least an hour trying to get the auto-download prompt working with canvas. That’s very cool you got it working properly.
Canvas2Image–;
I was expecting a cross-browser solution. :-\
Is there any length limit of “data” field in src? It would be great to have similar lib in IE.
If you combine this with http://fuchsia-design.com/CanvaSVG/, you effectively have a way to convert SVG to Canvas to Bitmap.
Example: http://antimatter15.110mb.com/misc/svg2bitmap/index.xhtml
BMP image generation is trivial. It’s been around for years. Beside it doesn’t need the slow-ish base64 encoding. However the size impact of base64 is stable ( always 4/3 ) as opposed to URL encoding ( depends on the characters and their frequency ).
thinpiglin: the limit is that of an SRC attribute, which I assume depends on the UA’s URL implementation.
Very useful! I thought this was only possible with Flash