With the introduction of Canvas, HTML5 has empower us to draw shapes, graphs, render texts, make gradients and patterns, manipulate images pixels, set an animations, even creating a stunning games! All this stuffs occur on the client side in the browsers. So let say you make an app that render some effects in a Canvas element and you want to allow user to take screenshot of the resut or save the result in your server for yourself.
Let’s digg how can we do it and save that canvas as an image in ther server using Rails.
Strategy 1 : Send canvas image as raw dataURL
The data URI scheme is a URI scheme that provides a way to include data in-line in web pages as if they were external resources. The
canvas.toDataURL() method returns the image data of the canvas as Data URI. And the Data URI has the image data Encodes with MIME base64.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Now lets render that canvas as an image.
As you can see, with that weird long url string something like
data:image/png;base64,iVBORw0KGgoA..., it render a png image. That long url is infact data uri which has image data encoded with MIME base64.
The format to be specific is data:[<mime type>][;charset=<charset>][;base64],< encoded data > .
Now, if we want to save that image in the server, we can just send that data uri as normal params and at the server, we can use ruby to decode that save that data as image file.
1 2 3 4 5 6 7 8 9
Strategy 2 : Send It as a Blob object
This method also use the dataURL but instead of send it as a raw text, we convert it to an image file object and send it. For this we use the Blob object. Simply it’s an object that represent a file-like object, so we create a blob object with the type PNG image, after we append this blob object to a FormData, and finally we send it through the jQuery Ajax Method.
1 2 3 4 5 6 7 8 9 10 11 12
We can now create a new FormData object, put our file on it and send our data using Ajax.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 2 3
So, that’s it.
This method is more appropriate and faster than the first one.
Those wondering how to mix this with carrierwave and paperclip, here are the links: