Simple HTML5 Drawing App + Saving The Files With Ajax

This is a simple drawing board app that allows user draw on a canvas, pick several brush sizes and colors and save his image (I'll leave part of the last to you).

You can see how this app works live on the Draw a Robot site. It uses HTML5 canvas and works in all modern browsers except Internet Explorer.

Some important parts of the javascript code are taken from this tutorial. William's app is more impressive. Mine is simpler and aims to explain it in understandable way (William's tutorial is a bit complex). Let's start:

Creating the canvas

<canvas id="drawingCanvas" width="550" height="450" style="border:1pt solid black;margin:auto;cursor:crosshair;clear:both;">

If you don't care about Internet explorer, that's it. We just add some styling to it and make the cursor crossed.

Create the brush sizes and color selectors

<div style="float:left;">Colors:</div> <a href="#" class="colorPicker" onclick="setColor('#FFF');return false;" style="background:#FFF;">&nbsp;</a>
<a class="colorPicker" href="#" onclick="setColor('#000');return false;" style="background:#000;">&nbsp;</a>
<a class="colorPicker" href="#" onclick="setColor('#FF0000');return false;" style="background:#FF0000;">&nbsp;</a>
<a class="colorPicker" href="#" onclick="setColor('#00FF00');return false;" style="background:#00FF00;">&nbsp;</a>
<a class="colorPicker" href="#" onclick="setColor('#0000FF');return false;" style="background:#0000FF;">&nbsp;</a>
<a class="colorPicker" href="#" onclick="setColor('#FFFF00');return false;" style="background:#FFFF00;">&nbsp;</a>
<a class="colorPicker" href="#" onclick="setColor('#00FFFF');return false;" style="background:#00FFFF;">&nbsp;</a>

<div style="clear:both;">&nbsp;</div>

<div style="float:left;">Sizes:</div>
<a href="#" class="colorPicker" onclick="setSize(2);return false;" style="width:2px;height:2px;margin-left:15px;">&nbsp;</a>
<a href="#" class="colorPicker" onclick="setSize(5);return false;" style="width:5px;height:5px;margin-left:15px;">&nbsp;</a>
<a href="#" class="colorPicker" onclick="setSize(10);return false;" style="width:10px;height:10px;margin-left:15px;">&nbsp;</a>
<a href="#" class="colorPicker" onclick="setSize(25);return false;" style="width:25px;height:25px;margin-left:15px;">&nbsp;</a>

<div style="clear:both;">&nbsp;</div>

<p style="clear:both;"><input type="button" value="Clear Canvas" onclick="clearCanvas();">
<input type="button" value="Save My Drawing" onclick="centerElt('saveDrawing',400,300);"></p>

This code adds size selection buttons, color selectiors, and button for saving.

Obviously you can use better CSS to save some code.

Note that Save my drawing users a function that is not published here to keep things simpler. It centers a popup on the screen. You can find or code such function yourself, or simply display the saving form under the canvas without fancy effects. (Let me know in the comments if you need clarification.

The save form

The save form is not important for this tutorial either. You can see the one at the Draw a Robot site, but the form can contain any fields you wish. Maybe image name, description, author name and so on.

The Javascript

After opening a javascript tag, you'll need the following code. I'll input all the explanations to it as javascript comments so you can directly copy the code and use it.

Please note: the javascript below depends on jQuery! If you don't store local copy of jQuery, you need to insert this code in the header of your page:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>

Now your javascript follows:

<script type="text/javascript">
/* some code used from http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/ */

/* Some global initializations follow. The first 2 arays will store all mouse positions 
on X and Y, the 3rd one stores the dragged positions. 
The variable paint is a boolean, and then follow the default values 
which we use to start */
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
var defaultColor="#000";
var defaultShape="round";
var defaultWidth=5;

// creating the canvas element
var canvas = document.getElementById('drawingCanvas');

    // Initaliase a 2-dimensional drawing context
    var context = canvas.getContext('2d');
    // set the defaults
    context.strokeStyle = defaultColor;
    context.lineJoin = defaultShape;
    context.lineWidth = defaultWidth;

// binding events to the canvas
  var mouseX = e.pageX - this.offsetLeft;
  var mouseY = e.pageY - this.offsetTop;
  paint = true; // start painting
  addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);

  // always call redraw

    addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);

// when mouse is released, stop painting, clear the arrays with dots
  paint = false;
  clickX = new Array();
  clickY = new Array();
  clickDrag = new Array();

// stop painting when dragged out of the canvas
  paint = false;

// The function pushes to the three dot arrays
function addClick(x, y, dragging)

// this is where actual drawing happens
// we add dots to the canvas
function redraw(){
  for(var i=0; i < clickX.length; i++)
    if(clickDrag[i] && i){
      context.moveTo(clickX[i-1], clickY[i-1]);
       context.moveTo(clickX[i]-1, clickY[i]);
     context.lineTo(clickX[i], clickY[i]);

// this is called when "clear canvas" button is pressed
function clearCanvas()
    // both these lines are required to clear the canvas properly in all browsers
    canvas.width = canvas.width;
    // we need to flush the arrays too
    clickX = new Array();
    clickY = new Array();
    clickDrag = new Array();

/* Two simple functions, they just assign the selected color and size 
to the canvas object properties */ 
function setColor(col)
    context.strokeStyle = col;

function setSize(px)

/* Finally this will send your image to the server-side script which will 
save it to the database or where ever you want it saved.
Note that this function should be called when the button in your save 
form is pressed. The variable frm is the form object. 
Basically the HTML will look like this:
<input type="button" value="Save Drawing" onclick="saveDrawing(this.form);">
function saveDrawing(frm)
    // converting the canvas to data URI
    var strImageData = canvas.toDataURL();  
        url: "", /* You need to enter the URL of your server side script*/
        type: "post",
          /* add the other variables here or serialize the entire form. 
          Image data must be URI encoded */
        data: "save=1&pic="+encodeURIComponent(strImageData), 
        success: function(msg)
           // display some message and/or redirect

Your server side script

It really depends on you. In the Draw a Robot site we just save the robots to the database and then display them in a gallery. You can save the image data in a blob field in the DB. Just have in mind that data / URI images are displayed with the following HTML code:

<img src="encoded image data">


  1. Replies
    1. Hey I just wanted to say that I really enjoyed reading your blog. You have good views, keep up the good informative info. Good Quality and very informative Blog! Contact Vinay Hari Education Consultant

  2. cool
    but trying to understand the script
    because i am having some errors in my facebook apps

    make a facebook application

  3. Great work came at a perfect time for me, html5 music playerwould be really cool if we could at least get an option to enable the HTML5 mode player in the next Subsonic release. Not only would it bypass the need for flash, but it also has some extra features (wav playback, etc).It seems the biggest issue would be with flv video, but by transcoding to mp4 instead of flv, that could be solved. Even without the video fix, making it optional would allow those of us the mainly use Subsonic for music to benefit from the new player.

  4. Nice post. Parents are parents, not Gods. Of course they cannot have all the answers. The way you explain things to your kids should do all the work…it all comes under parenthood and your people skills.

  5. hi, how do i save to database? using phpmysql, what params do i set my form?

    thanks for great script

  6. This is actually quite wrong - why do you remember every single point you need to draw and redraw ALL of them after every single movement? All you need to remember is last point and if button was down at that point, then move/draw from last to current point. You don't need to remember all points and you definetly don't need redraw them over and over again.

  7. Good overview, Lee. Using a tool such as can be helpful in assessment and identifying areas of need.

    Website Development company

  8. You will discover some fascinating points in time in this post but I don’t know if I see all of them interior to heart. I am learning great extra challenging on distinct blogs everyday. Lots of people will be benefited from your writing. Cheers!

    Press Release Writers
    Press Release Writing Service

  9. Just like what your website title is. This is really cool. Write something on web development Philippines next time. Thank you.

  10. paint for mac MyBrushes paint for Mac app is the best Mac paint software to paint on Mac infinite canvas and PLAYBACK drawing Paintbrush for Mac.It's good as ms Paint for Mac
    Drawing App MyBrushes is the Best drawing app for ipad to paint on infinite canvas and PLAYBACK each drawing stroke on iPad, iPhone. Download best drawing app for iPad Now.
    avi to mp4 converter Total Video Converter, a very powerful Avi to Mp4 Video Converter, convert any video files to avi, 3gp, mp4, psp, iPod, iPhone, flv, DVD, VCD...

  11. Drawing App : Best drawing app for ipad to paint on infinite drawing canvas and PLAYBACK every drawing stroke on iPad and iPhone. Visit MyBrushes-App.com for best drawing app.

  12. Nice blog Very useful information is providing by ur blog. Great beginning html tutorials Very clear and helpful for beginners.

  13. These all are notable facts… I stick with responsive website design for my business. With the mobile marketing is at its peak stage, having website that goes comfy on all devices will help your business. You can check my website for more details on the importance of responsive website design. PHP Training in Chennai | Best PHP training in Chennai | PHP Training Institute in Chennai

  14. Thanks for your informative article. Your blog is loaded with awesome information. Please include RSS field shat that we can receive your latest post direct to my inbox. Wordpress Course in Chennai

  15. Thanks for a great information in your blog.I have read all the post of your blog.Great work on PHP

  16. Thanks for the great information in your blog PHP

  17. Best SQL Query Tuning Training Center In Chennai This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..

  18. Great..You have clearly explained about Simple HTML5 Drawing App + Saving The Files With Ajax..Its very easy to understand..Keep on sharing..
    PHP training in chennai

  19. Thanks for sharing this informative information...You may also refer....
    How to migrate from a typical HTML4 page to a typical HTML5 page.

  20. My friend Suggest me this blog and I can say this is the best blog to get the basic knowledge.Thank you so much for this Selenium Training in Chennai


  21. Thank you for the info. It sounds pretty user friendly. I guess I’ll pick one up for fun. thank u

    iPad Service Center in Chennai - Service Locations

  22. Thanks for sharing this informative information...You may also refer....
    oracle training in chennai

  23. Well explained. Got to learn new things from your Blog on Appium.Appium training in chennai

  24. Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

    iOS Training in Chennai

  25. Thank You for sharing your article. I like it. We provide TIBCO Online Training in Hyderabad.


  26. Hai Author Good Information that i found here,do not stop sharing and Please keep updating us..... Thanks

  27. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

  28. I am expecting more interesting topics from you. And this was nice content and definitely it will be useful for many people.

    Android App Development Company

  29. Thanks for your information and valuable time . Great article. much more helpful to all.
    Android Training in chennai

  30. I am expecting more interesting topics from you. And this was nice content and definitely it will be useful for many people.
    iOS App Development Company
    iOS App Development Company

  31. These ways are very simple and very much useful, as a beginner level these helped me a lot thanks fore sharing these kinds of useful and knowledgeable information.
    Fitness SMS
    Fitness Text
    Salon SMS
    Salon Text
    Investor Relation SMS
    Investor Relation Text

  32. great and nice blog thanks sharing..I just want to say that all the information you have given here is awesome...Thank you very much for this one.
    web design Company
    web development Company
    web design Company in chennai
    web development Company in chennai
    web design Company in India
    web development Company in India

  33. it is really amazing...thanks for sharing....provide more useful information...
    Mobile app development company

  34. This comment has been removed by the author.

  35. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.

    Best Java Training Institute Chennai

  36. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.

  37. I simply wanted to thank you so much again. I am not sure the things that I might have gone through without the type of hints revealed by you regarding that situation.
    Best Python training Institute in chennai

  38. Nice blog with excellent information. Thank you, keep sharing. Full Stack Training in Hyderabad

  39. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts, have a nice weekend!
    Hadoop Training in Chennai

  40. I wish to show thanks to you just for bailing me out of this particular trouble.As a result of checking through the net and meeting techniques that were not productive, I thought my life was done.

    ccna training in chennai

    ccna training in bangalore

    ccna training in pune

  41. Thank you for this post. Thats all I are able to say. You most absolutely have built this blog website into something speciel. You clearly know what you are working on, youve insured so many corners.thanks
    java training in annanagar | java training in chennai

    java training in marathahalli | java training in btm layout

    java training in rajaji nagar | java training in jayanagar

  42. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.

    rpa training in Chennai | rpa training in pune

    rpa training in tambaram | rpa training in sholinganallur

    rpa training in Chennai | rpa training in velachery

    rpa online training | rpa training in bangalore

  43. I really like the dear information you offer in your articles. I’m able to bookmark your site and show the kids check out up here generally. Im fairly positive theyre likely to be informed a great deal of new stuff here than anyone
    python training in tambaram
    python training in annanagar
    python training in OMR

  44. This comment has been removed by the author.

  45. Thanks Admin for sharing such a useful post, I hope it’s useful to many individuals for developing their skill to get good career.
    java training in chennai | java training in bangalore

    java online training | java training in pune

  46. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.

    angularjs Training in online

    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in btm

  47. I prefer to study this kind of material. Nicely written information in this post, the quality of content is fine and the conclusion is lovely. Things are very open and intensely clear explanation of issues

    Data Science course in kalyan nagar | Data Science course in OMR
    Data Science course in chennai | Data science course in velachery
    Data science online course | Data science course in jaya nagar

  48. I am really happy with your blog because your article is very unique and powerful for new reader.
    Click here:
    Selenium Training in Chennai | Selenium Training in Bangalore | Selenium Training in Pune | Selenium online Training

  49. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    python online training
    python training in OMR
    python training course in chennai

  50. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    Devops Training in pune

  51. I am really very happy to find this particular site. I just wanted to say thank you for this huge read!! I absolutely enjoying every petite bit of it and I have you bookmarked to test out new substance you post.

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    angularjs Training in bangalore

    angularjs Training in bangalore

  52. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.

    AWS Training in Velachery | Best AWS Course in Velachery,Chennai

    Best AWS Training in Chennai | AWS Training Institutes |Chennai,Velachery

    Amazon Web Services Training in Anna Nagar, Chennai |Best AWS Training in Anna Nagar, Chennai

    Amazon Web Services Training in OMR , Chennai | Best AWS Training in OMR,Chennai

  53. And indeed, I’m just always astounded concerning the remarkable things served by you. Some four facts on this page are undeniably the most effective I’ve had.
    safety courses in chennai

  54. Really you have done great job,There are may person searching about that now they will find enough resources by your post
    Best Devops Training in pune

  55. Resources like the one you mentioned here will be very useful to me ! I will post a link to this page on my blog. I am sure my visitors will find that very useful
    python training institute in marathahalli | python training institute in btm | Data Science training in Chennai

  56. I’d love to be a part of group where I can get advice from other experienced people that share the same interest. If you have any recommendations, please let me know. Thank you.
    nebosh course in chennai

  57. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    angularjs Training in chennai

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    angularjs Training in bangalore

  58. I believe that your blog will surely help the readers who are really in need of this vital piece of information. Waiting for your updates.
    Selenium Training in Bangalore
    Selenium Training Institutes in Bangalore
    Selenium Course in Bangalore

  59. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
    Best Devops training in sholinganallur
    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram

  60. I feel really happy to have seen your webpage and look forward to so many more entertaining times reading here. Thanks once more for all the details.
    iosh safety course in chennai


  61. It seems you are so busy in last month. The detail you shared about your work and it is really impressive that's why i am waiting for your post because i get the new ideas over here and you really write so well.

    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training
    Selenium training in bangalore

  62. Amazing article. Your blog helped me to improve myself in many ways thanks for sharing this kind of wonderful informative blogs in live. I have bookmarked more article from this website. Such a nice blog you are providing ! Kindly Visit Us @ Best Travels in Madurai | Tours and Travels in Madurai | Madurai Travels

  63. I usually read them, take what I think is useful, what tool may suit me, and try to be creative about it in order to fit my needs.

    Many times things are oriented towards others things that I'm interested in.

    But may I say, I found the approach of this article uniquely outstanding. Speaks to me plain, simple, expressing ideas without the need of "marketing induced words" which do not mean nothing unless you unwrap them.https://nareshit.in/html-javascript-training/

  64. Thanks for sharing the steps to write an e-commerce blog. I think this is very useful especially for beginners.
    All those who are into e-commerce and wants to know more about it and re-commerce....best regards.
    QuickBooks Training in hyderabad

  65. This is best one article so far I have read online, I would like to appreciate you for making it very simple and easy
    Devops Training in Chennai | Devops Certification in Chennai

  66. This comment has been removed by a blog administrator.

  67. The post is written in very a good manner and it entails many useful information for me. I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept.

    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

  68. Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.
    apple service center chennai
    apple service center in chennai
    apple mobile service centre in chennai
    apple service center near me


  69. read this above post its very greatful for me thanks sharing this post ,great post.
    Best Ice Fishing Gloves Best Ice Fishing Gloves Best Ice Fishing Gloves

  70. thank your valuable content.we are very thankful to you.one of the recommanded blog.which is very useful to new learners and professionals.content is very useful for hadoop learners

    Best Spring Classroom Training Institute
    Best Devops Classroom Training Institute
    Best Corejava Classroom Training Institute
    Best Advanced Classroom Training Institute
    Best Hadoop Training Institute
    Best PHP Training Institute

  71. Thank your valuable content.we are very thankful to you.one of the recommended blog.which is very useful to new learners and professionals.content is very useful for hadoop learners

    Best Spring Online Training Institute
    Best Devops Online Training Institute
    Best Datascience Online Training Institute
    Best Oracle Online Training Institute
    Best AWS Online Training Institute

  72. Thanks For Sharing The Information The Information Shared Is Very Valuable Please Keep Updating Us Time Just Went On Reading The article Python Online Course Hadoop Online Course Aws Online Course Data Science Online Course

  73. It is a great post. Keep sharing such kind of useful information.

    Guest posting sites

  74. A bewildering web journal I visit this blog, it's unfathomably heavenly. Oddly, in this present blog's substance made purpose of actuality and reasonable. The substance of data is informative
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training


  75. Thank you for sharing the article. The data that you provided in the blog is informative and effective. Best Devops Training Institute

  76. A befuddling web diary I visit this blog, it's incredibly grand. Strangely, in this present blog's substance made motivation behind fact and sensible. The substance of information is instructive
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

  77. Great post i must say thanks for the information you added to this post. I appreciate your post and looking forward for more.

    ExcelR Data Science in Bangalore

  78. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!
    ExcelR Data science courses in Bangalore


  79. You might comment on the order system of the blog. You should chat it's splendid. Your blog audit would swell up your visitors. I was very pleased to find this site.I wanted to thank you for this great read!!


  80. Super site! I am Loving it!! Will return once more, Im taking your food likewise, Thanks.
    Data Science Course in Pune

  81. very helpful information sharing...

  82. Alleyaaircool is the one of the best home appliances repair canter in all over Delhi we deals in repairing window ac, Split ac , fridge , microwave, washing machine, water cooler, RO and more other home appliances in cheap rates

    Window AC Repair in vaishali
    Split AC Repair in indirapuram
    Fridge Repair in kaushambi
    Microwave Repair in patparganj
    Washing Machine Repair in vasundhara
    Water Cooler Repair in indirapuram
    RO Service AMC in vasundhara
    Any Cooling System in vaishali
    Window AC Repair in indirapuram

  83. Get the best nursing services baby care services medical equipment services and allso get the physiotherapist at home in Delhi NCR For more information visit our site

    nursing attendant services in Delhi NCR
    medical equipment services in Delhi NCR
    nursing services in Delhi NCR
    physiotherapist at home in Delhi NCR
    baby care services in Delhi NCR

  84. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!

  85. I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post. Hats off to you! The information that you have provided is very helpful.
    How to Start A blog 2019
    Eid AL ADHA