HTML5 canvas export as png or jpeg

Hello, Today we will see how we can export our canvas to an image in well known formats png jpeg I will also give you a trick to download a file the HTML5 way using the new download attribute that ships with HTML5 out of the box Lets start with declaring our markup The Markup [crayon-66238034adff2860255027/] Above markup is pretty much what I have used in my previous posts so it must be now familiar to you. Notice our anchor tag has a click event handler. Lets now check what JavaScript functionality is required. There are gazillion ways to do what I have done below so don't judge on the code but rather see how our problem is solved.   The JavaScript [crayon-66238034adff8409724435/] So we are just drawing a string "This canvas will be exported" on our canvas and our exportCanvas() method is responsible for exporting our canvas to an image file that opens in new window from where users can right click on the image and save it on their disk. Notice this line [crayon-66238034adff9213856030/] Thats where we are telling our canvas function to export it as png file. To export it as jpeg do this instead [crayon-66238034adffb380610472/] Demo Above is just a basic usage example. But you should get an idea Another way to force download an image using JavaScript would be to feed our canvas data URL to an anchor href with download attribute as shown below The Markup (method 2 - force download) Be aware that this works only on browsers that supports download attribute such as Google Chrome. We will change our exportCanvas() method in a sec. [crayon-66238034adffc093545182/] The Javascript Updated exportCanvas() method is shown below [crayon-66238034adffd745618537/] Remember that this is just a pointer. How you end up using above functionality is solely upto you. Also remember that download attribute is not supported in majority of … [Read more...]