HTML canvas element (HTML5) be used to draw 2D shapes using Javascript. Once a shape is drawn, it can also be converted to an image (png, jpeg, etc.) and can be embedded in the HTML page using <img> tag and hence can also be downloaded. Here are the steps to achieve this:
- First create an empty canvas element as shown below:
<canvas id="canvasid" width="200" height="100"></canvas>
- Then draw some basic shape in it. Here is the javascript code to draw a simple square:
var canvas = document.getElementById('canvasid'); var context = canvas.getContext('2d'); context.fillStyle="#ff0000"; context.fillRect(10,10,60,60);
- Now using canvas
toDataURL("image/png")
get the png image url and populate the src attribute of required image. You may also want to see Canvas element reference. Here is how the code looks like:
<img id="canvasimg" src="" /> <script type="text/javascript"> $("#canvasimg").attr("src", $("#canvasid").get(0).toDataURL("img/png")); </script>
Note that the value returned bytoDataURL("image/png")
looks something like this:data:image/png;base64,iVBORw0KGgo.....
- Here is how the final image looks like:
You can see the live demo at Canvas to image example. - To download the image, you can right click on it and download as a regular image.
Notes on browsers compatibility
Canvas being HTML5 element is not supported by old browsers like IE8. It should work in browsers like Chrome, Firefox, IE9, etc. which support HTML5.