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-5b28a683514ea438728936/] 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-5b28a683514ff641851696/] 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-5b28a68351507823771673/] Thats where we are telling our canvas function to export it as png file. To export it as jpeg do this instead [crayon-5b28a6835150e122155926/] Demo http://jaspreetchahal.org/examples/html5/canvas-image-export.html 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-5b28a68351515606839380/] The Javascript Updated exportCanvas() method is shown below [crayon-5b28a6835151b259052961/] 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...]