HTML5 is the latest technology in web today. We create lots of interesting thing with HTML5.  In this post i explain you how to create a simple HTML5 based web application for drawing using canvas.

HTML5 Canvas

HTML5 Canvas is used to draw graphics on fly using javascript. The canvas element is only a container for graphics. You must use a script to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images. To learn more about canvas follow this link.

Example: To write some thing inside canvas use this

In this above example i first create canvas tag and set height and width and assign id to canvas. After this i include jQuery from google cdn. Now inside <script> first i find canvas in document i need to write something after that call some predefined method like font, textAlign etc. to make my word look nice.

Now i explain you how to make a simple web based paint application

Create a <canvas> inside body.

Create some option we used for drawing like pen size, clear canvas, eraser etc.

Include jQuery Library file.

Now we write some javascript code to get or application working.

In above code first i get my selected color to draw image so i trigger event to get that thing.

Now get our selected color i get my canvas ready to draw picture on it

Now we need to handle some events over canvas like

  • mousedown
  • mousemove
  • mouseup
  • mouseleave

When user mouse is down and move over canvas you need to start create image or when user mouse is up and leave you need to stop. In above code i create two main function which are responsible to get mouse position and to draw image.

Complete Code: