HTML5 Tutorial: How to Get and Set a Base64 Image on Canvas using toDataURL

Updated on October 17, 2016

For many web applications it can be useful to turn the visual image on a HTML5 canvas into a base64 representation of it which can be sent and shared. As this tutorial will show you, that is not very difficult and it is also very simple to load a base64 image onto a HTML5 canvas. The method toDataURL() of a canvas plays an important role in this process and I'll show you how to use it.

In this tutorial you'll see both techniques for converting an image to base64 and how to go from base64 to an image. I'll also discuss some possible ways this functionality can be used in interactive websites.

How about a website where you can share your own images with others - such functionality is easily implemented with the techniques described in this tutorial. I will give several other examples later in this tutorial.

What is the HTML5 canvas?

The HTML5 canvas is one of my favorite additions to the HTML web standard. With it you can write some JavaScript code to draw directly on your webpages. I have written several tutorials that explain the basics of how to draw on a canvas and how to do various things, like creating text, circles and arcs:

What is base64?

Base64 is a way of representing data using only readable characters like letters, numbers and some symbols like the plus symbol. This data can be anything, like an image or a file, but commonly it is data that is not plain text (otherwise there is not much point in converting it to base64, is there?).

This representation, also known as a base64 string, is very useful because it can be used anywhere that normal text can also be used. It makes it easier to store the images - you can have several images in a plain text file for example.

The exact details of how base64 works are not relevant for this tutorial. All that matters is that base64 is a different way of representing the same visual image data but in a textual way. I'll refer the interested reader to the base64 article on Wikipedia if you want to know more.

How to get canvas image data using toDataURL()

The canvas in HTML5 has a method called toDataURL() that you can call to turn a HTML5 canvas into a PNG image and to get the image data of that canvas. By default it will give you a base64 representation of the image in PNG format. In simpler terms: you will get a PNG image but it has been encoded in base64. For the toDataURL() method, the PNG format is the only image format that is supported by all HTML5-compliant web browsers. Some browsers support multiple image formats.

You can call toDataURL with an argument, such as "image/jpeg" or "image/png" if you want to specify which image format you want. We don't need to worry about this and we can simply call toDataURL without arguments to get a PNG image in base64 representation. Be aware that the HTML5 standard only requires browsers to support PNG for toDataURL so it is best to use that image format if you want to make your code work in all web browsers.

In the following code we have a canvas and we are calling the toDataURL() method to get the image data:

<canvas id="mycanvas" width="300" height="300">
</canvas>
<script type="text/javascript">
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 100, 50, 1.5 * Math.PI, 0.5 * Math.PI, false);
ctx.lineWidth = 10;
ctx.stroke();
var imgData = canvas.toDataURL();
</script>
Our visual image
Our visual image

The variable imgData now contains a base64 representation of the image currently on the canvas. It looks something like this: data:image/png;base64,iVBORw0 ... AAAElFTkSuQmCC. I have only shown the beginning and the end of the data because it would be too much to show it all. As you can see it starts with "data:", then the image type ("image/png"), then the encoding ("base64") and finally all the data of the image in text.

Simply by calling toDataURL() we have turned the image into a textual representation. That's a good thing because text is a lot easier to share or to send. In fact, if you were to copy this whole textual representation of the image and you would send it to someone else, they can paste it into the address bar of their browser and they will see the image.

What can we do with toDataURL()?

What can we do with this data?

  • We could send the base64 string to the server for storage in a database. A user could create an image, using a HTML5 canvas image editor, and the image could be submitted to the website. The image could be stored as base64 string in the database and it can easily be loaded and displayed on a canvas again (see later in this tutorial on how to do this). People could create and shart art this way.
  • We can create undo / redo functionality for such a canvas image editor. You could keep track of all the edits that the user does and you could save every version of the image as a base64 string. If the user made a mistake and wants to undo the most recent edit then you can load the latest base64 and show it on the canvas.
  • A "send image by email" functionality. As you may or may not know, base64 is also used when you attach an image (or any file for that matter) to an email. A website could now offer the ability to send an image to your friends by email. It simply receives the image from you in base64 representation and then it composes an email with that base64 data included.

How to load base64 image data on a HTML5 canvas

You now also want to do the reverse: if you have a base64 representation of an image, how can we load that base64 image data onto a HTML5 canvas? This is not difficult because we can simply create an Image, assign the data to that image and then draw the image. Here is the JavaScript code to do just that:

var myImage = new Image();
myImage.src = imgData;
ctx.drawImage(myImage, 0, 0);

The variable imgData contains the base64 image data. If the canvas was previously empty, you will now see our image once more on the canvas. After that you can use toDataURL() again to get the data in base64 representation.

Conclusion

In this tutorial we have seen how to take the image that is displayed on a HTML5 canvas, how to turn it into a base64 string and how to do the reverse: we have seen how to load a base64 image on a HTML5 canvas. What you do with those base64 strings is totally up to you!

Good luck with your web development projects and happy coding!

Questions & Answers

    Comments

      0 of 8192 characters used
      Post Comment

      • profile image

        soegaraedy 

        5 years ago

        To Joe Lannen,

        Be sure that the parameter mycanvas in:

        var canvas = document.getElementById('mycanvas');

        is the id of your canvas HTML element:

        canvas id="mycanvas"

      • profile image

        Joe Lannen 

        5 years ago

        What if toDataUrl only outputs 'data:'... without the rest of the string? I have the canvas image opening in a new window, and it shows correctly, but URL has no data, so I'm unable to send to server. hmmm.

      • profile image

        Rajeev Kumar verma 

        6 years ago

        all newspapers & magazine association

        We are pleased to inform you that ‘All Newspapers & Magazines Association’ has been formed under the patronage of ‘International Media Production Zone’ of India Media City with an aim: *To provide a firm platform for publishing industry *To bring publishers together to discuss the main issues facing the industry *To define the practical policies that will take the industry forward The opportunity to serve as the volunteer leader of a trade, professional, newspaper & magazine association is a significant lifetime honor that carries many rewards.

        http://www.ifaaassociation.com/

      • InduswebiTech profile image

        InduswebiTech 

        6 years ago from Rama Road, Kirti Nagar, New Delhi, India

        i tried this coding but it wont worked.. is there any special editor for html5

      • profile image

        Ton Groeneveld 

        7 years ago

        I am sorry but...

        var myImage = new Image();

        myImage.src = imgData;

        ctx.drawImage(myImage, 0, 0);

        ...won't work reliably. You will have to use myImage.onLoad=function(){ctx.drawImage(myImage, 0, 0);} in order to have your Javascript waiting for the load to be completed.

      working

      This website uses cookies

      As a user in the EEA, your approval is needed on a few things. To provide a better website experience, turbofuture.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

      For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://turbofuture.com/privacy-policy#gdpr

      Show Details
      Necessary
      HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
      LoginThis is necessary to sign in to the HubPages Service.
      Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
      AkismetThis is used to detect comment spam. (Privacy Policy)
      HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
      HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
      Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
      CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
      Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
      Features
      Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
      Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
      Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
      Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
      Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
      VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
      PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
      Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
      MavenThis supports the Maven widget and search functionality. (Privacy Policy)
      Marketing
      Google AdSenseThis is an ad network. (Privacy Policy)
      Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
      Index ExchangeThis is an ad network. (Privacy Policy)
      SovrnThis is an ad network. (Privacy Policy)
      Facebook AdsThis is an ad network. (Privacy Policy)
      Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
      AppNexusThis is an ad network. (Privacy Policy)
      OpenxThis is an ad network. (Privacy Policy)
      Rubicon ProjectThis is an ad network. (Privacy Policy)
      TripleLiftThis is an ad network. (Privacy Policy)
      Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
      Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
      Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
      Statistics
      Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
      ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
      Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)