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-5ab7138b05816342068656/] 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-5ab7138b05827845972594/] 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-5ab7138b0582f534584189/] Thats where we are telling our canvas function to export it as png file. To export it as jpeg do this instead [crayon-5ab7138b05835838754827/] 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-5ab7138b0583b538788283/] The Javascript Updated exportCanvas() method is shown below [crayon-5ab7138b05841421931131/] 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...]