- HTML5 canvas export as png or jpeg
- The JavaScript
- Demo
- The Markup (method 2 – force download)
- The Javascript
- Demo
- Share this post with your friends
- Related
- Comments
- Leave a Reply Cancel reply
- How to save HTML Canvas as an Image
- Downloading a Canvas as an Image
- How toDataURL() works
- Saving images from canvas as other formats
- Conclusion
- More Tips and Tricks for HTML
- Как преобразовать тег canvas в изображение и обратно?
- Преобразование тега сanvas в изображение
- Комментарии ( 0 ):
- Vanilla JavaScript save canvas as an image
- Live Code example in Codepen permalink
- 1. Canvas to Image with Right-click to save permalink
- 2. Download the button to save an image from the canvas permalink
- Browser Support permalink
- Thank you for reading, and let’s connect! permalink
HTML5 canvas export as png or jpeg
Your browser does not support HTML5 Canvas . Try downloading latest Chrome , Firefox , Safari , Opera or Internet explorer .
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
//img = img.replace(«image/png»,»image/octet-stream»); // force download, user would have to give the file name.
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.
Thats where we are telling our canvas function to export it as png file. To export it as jpeg do this instead
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.
The Javascript
Updated exportCanvas() method is shown below
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 browsers yet so be aware relying on this method.
Here you are with the demo of what we did above. Try it in Google Chrome
Demo
Force download canvas as png or jpeg image with filename. Remember that our filename is what we set in download attribute as shown below
In case you want to improve on what I mentioned or if I got any fact wrong please leave your comments as It will be helpful to others too. I am also learning everyday so learning together and sharing experiences is fun.
Share this post with your friends
Related
Comments
I want to export to jpg, even if I used:
var img = mycanvas.toDataURL(“image/jpeg;base64;”);
IE 10, IE 11 does not work, still get png file. Pleases for any help
Hey Jaspreet, Neat post. Especially liked the concise way in which you explained multiple ways of downloading the canvas. In case you haven’t noticed, http://jaspreetchahal.org/examples/html5/canvas-image-export2.html also links to the first example itself. But when I copy and paste the above URL, the second example shows up, so that was useful. Thanks a lot! This has been very useful to me!
I’m not sure where to start…
A) I love your site and how you explain things!
B) I design web pages as a hobby, among other stuff, and have yet to see such a skillful use of serif fonts! (I’m not really a fan of them…)
C) Can I give the site 5-star ratings until it’s rated at 5?
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
How to save HTML Canvas as an Image
Canvas gives us a lot of flexibility to create great, code generated graphics, and sometimes we need to download them as images. Fortunately, this is quite easy with HTML canvas. Here is an example, where clicking the button downloads the canvas as an image:
Let’s look at how this works.
Downloading a Canvas as an Image
In the example above, we’ve created a canvas image and a button you can click to download it. This button uses toDataURL() to convert our canvas to an image URL data string. When we click on it we get our original canvas, and then create an anchor to download it immediately:
let canvas = document.getElementById('canvas'); let ctx = canvas.getContext('2d'); // Canvas code goes here // . document.getElementById('download').addEventListener('click', function(e) // Convert our canvas to a data URL let canvasUrl = canvas.toDataURL(); // Create an anchor, and set the href value to our data URL const createEl = document.createElement('a'); createEl.href = canvasUrl; // This is the name of our downloaded file createEl.download = "download-this-canvas"; // Click the download button, causing a download, and then remove it createEl.click(); createEl.remove(); >);
Javascript struggles a bit with native downloads, so we are emulating a link click instead. We do that by creating the anchor using createElement , and then using click() to click on it. This achieves the same outcome.
The key thing to remember is to use toDataURL , which encodes our image data as a string that is easily downloaded.
How toDataURL() works
toDataURL() converts a canvas element to a long image encoding string. Let’s look at our example:
// Convert our canvas to a data URL let canvasUrl = canvas.toDataURL(); console.log(canvasUrl); // Outputs // "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABRQAAANSCAYAAAAUN0KjAAAAAXNSR0IArs4c6QAAIABJREFUeF7sfVuSJLeOrNrsaP/7GM227pmZVehaZTxIgni.
By default, toDataURL() creates a png image. But fortunately it has options to let us change that if we want.
Saving images from canvas as other formats
toDataURL(type, encoderOptions) has two arguments which lets us change the way the canvas is encoded. This lets us save files as other formats, such as jpg.
Those two arguments can be defined as follows:
- type , which is a filetype, in the format image/png .
- encoderOptions , which is a number between 0 and 1, defining the image quality. This is only supported by file formats that have lossy compression, like webp or jpg.
For example, if we wanted to save our image as a .jpg with a quality of 59% , we could write the following:
// Convert our canvas to a data URL let canvasUrl = canvas.toDataURL("image/jpeg", 0.5); console.log(canvasUrl); // Outputs // "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAQwAABtbnRyUkdCIFhZWiAAAAAAAAAAAAAAAABhY3NwAAAAAA.
By default, all browsers support image/png . Other formats, like image/jpeg and image/webp are widely supported. Support on image/webp can be found here.
Conclusion
Saving canvas elements as images is straightforward and only relies on toDataURL . If you want to learn about saving canvas images in a real world setting on the backend, you can read my tutorial on that here.
More Tips and Tricks for HTML
Как преобразовать тег canvas в изображение и обратно?
При работе с графикой в браузере, часто не обойтись без использования тега canvas. В данной статье речь пойдет о том, как конвертировать изображение в тег canvas или как преобразовать содержимое тега canvas в изображение.
Для преобразования изображения в тег canvas, необходимо использовать метод drawImage, предоставляемый контекстом элемента canvas:
// Конвертирует изображение в canvas
// параметр image – это ссылка на изображение в html документе
var cnvs = document.createElement(«canvas»);
cnvs.width = image.width;
cnvs.height = image.height;
cnvs.getContext(«2d»).drawImage(image, 0, 0);
Аргументы 0, 0 соответствуют координатам на холсте, где должно быть размещено изображение.
Преобразование тега сanvas в изображение
Обратите внимание на тот факт, что функция convertCanvasToImage должна иметь параметр callback, представляющий собой функцию обратного вызова, поскольку для загрузки данных в параметр src, требуется некоторое время. Таким образом, возвращенное изображение может быть пустым.
// конвертирование canvas в изображение
function convertCanvasToImage(canvas, callback)
image.onload = function() image.src = canvas.toDataURL(«image/png»);
image.crossOrigin = «anonymous»;
>
В функции callback можно выполнить AJAX запрос на сервер, для сохранения данных в файл.
Вот так просто происходит конвертирование canvas в изображение и обратно!
Создано 08.01.2019 13:40:58
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
- Кнопка:
Она выглядит вот так: - Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт - BB-код ссылки для форумов (например, можете поставить её в подписи):
Комментарии ( 0 ):
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.
Vanilla JavaScript save canvas as an image
Guide explaining how exporting our Canvas drawing as an image to download. Try the Codepen to see yourself.
Yesterday, we started our introductory canvas course.
In this JavaScript tutorial, we will learn how to save the canvas as an image and download it.
So how do we convert the canvas to export it as an image?
There are two ways of doing this. And we will explore both.
Live Code example in Codepen permalink
1. Canvas to Image with Right-click to save permalink
Everyone knows this option, but we can right-click on the canvas to save it as an image.
This will only work in specific browsers. That’s why it’s not the correct way of saving the image.
Note: Keep in mind the canvas has no background!
2. Download the button to save an image from the canvas permalink
The second solution is to add a download button to our page. The button will then export the canvas content and open the base64 image in another tab. And from there, you can download the image.
canvas id="canvas" height="200">canvas> br /> button id="download">Downloadbutton>
Now let’s add the button variable to our JavaScript code:
const download = document.getElementById('download');
Awesome. We need to add an eventListener to it and listen to the click command.
download.addEventListener('click', function (e) const link = document.createElement('a'); link.download = 'download.png'; link.href = canvas.toDataURL(); link.click(); link.delete; >);
We create a temporary link href on which we will place the canvas’s data URL and then click it.
We are using the toDataURL function, which returns a base64 image string that looks something like this:
// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby // blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
Browser Support permalink
The canvas element is well supported these days and is defiantly a good option if you want to draw vectors on screen.
Thank you for reading, and let’s connect! permalink
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter