- First create an empty canvas element as shown below:
<canvas id="canvasid" width="200" height="100"></canvas>
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:
toDataURL("image/png")looks something like this:
- 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.