Click here to Skip to main content
15,867,453 members
Articles / Web Development / HTML
Tip/Trick

Saving and Loading HTML5 Canvas Images

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
20 Jun 2014MIT 7.8K   3  
Code for loading and saving images in an HTML5 canvas via Base64

Introduction

I had a request to update a jQuery plugin (dooScrib) so that you can get a Base64 string for the image created and came about with these snippets. Eventually, the plugin will get updated to include them.

Background

I am trying to move all of my personal code snippets into Gists and then I also figured I would share them as tips here.

As time progresses, you can find more here.

Using the Code

Here is the snippet to convert an image into a Base64 string:

JavaScript
function convertImgToBase64(id, outputFormat){
  var canvas = document.createElement(id);
  var imageDataURL = canvas.toDataURL(outputFormat || 'image/png');
  
  return imageDataURL;
}

With that snippet developed, I just knew that a request would come along to reverse the process. The following snippet will take a Base64 string and convert it back into an image:

JavaScript
function convertBase64toImage(id, image64) {
  var canvas = document.createElement(id);
  var context = canvas.getContext('2d');
  
  var baseImage = new Image();
  
  baseImage.onload() = function() {
    context.drawImage(baseImage, 0, 0);
  };
  
  baseImage.src = image64;
}

Conclusion

Happy coding!!!

History

  • 20-Jun-2014 - Initial release

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer
United States United States
I am software developer with over 20 years of professional experience. I have been employed as a software developer since the early 90′s back when Microsoft’s Windows 3.1x was gaining popularity and IBM’s OS/2 was the predominant leader in 32-bit PC based Operating Systems.

Prior to choosing this as my profession I had studied architecture and then later Electrical and Mechanical engineering in college. As a young kid growing up I always played with computers, my first computer was a TRS-80 that I would spend countless hours writing programs for, I never really thought of programming as a profession. The story goes that in my final year of college I took a C/C++ programming class and had so much fun working on the various projects that my professor told me something that changed everything.

“You know they pay people to do stuff like this for a living?” – Professor Bolman

Check out my blog here.

My current and ever evolving projects:

jqAlert javascript alerts done right for those using jQueryUI.
DooScrib Doodle and scribble pad written in javascript for use with HTML5 Canvas.

Comments and Discussions

 
-- There are no messages in this forum --