JavaScript Canvas Image Conversion

At last week's Mozilla WebDev Offsite, we all spent half of the last day hacking on our future Mozilla Marketplace app. One mobile app that recently got a lot of attention was Instagram, which sold to Facebook for the bat shit crazy price of one billion dollars. Since I wouldn't mind having a bill in my back account, I decided to create an Instagram-style app (which I'll share with you in the future). This post details how you can convert an image to canvas and convert a canvas back to an image.

Convert an Image to Canvas with JavaScript

To convert an image to canvas, you use a canvas element's context's drawImage method:

// Converts image to canvas; returns new canvas element
function convertImageToCanvas(image) {
	var canvas = document.createElement("canvas");
	canvas.width = image.width;
	canvas.height = image.height;
	canvas.getContext("2d").drawImage(image, 0, 0);

	return canvas;
}

The 0, 0 arguments map to coordinates on the canvas where the image data should be placed.

Convert Canvas to an Image with JavaScript

Assuming modifications to the image have been made, you can easily convert the canvas data to image data with the following snippet:

// Converts canvas to an image
function convertCanvasToImage(canvas) {
	var image = new Image();
	image.src = canvas.toDataURL("image/png");
	return image;
}

The code above magically converts the canvas to a PNG data URI!

Alas, converting an image to canvas and canvas to an image is probably much easier than you think. In future posts, I'll detail how you can apply different image filters to your canvased image. In the mean time, start buying fancy cars and houses with the future billion you'll have!