Friday, February 17, 2012

HTML5 Canvas Drawing Library

This library will allow you to create as many Canvas elements as you wish on a single page. It does not matter if you have the canvas element inside multiple elements or if the page is too long (scrollable).

There are  a few tutorials online on how to create a canvas drawing app but most assume that you are placing them on a regular HTML page. I tried most of them but since I wanted to use it in my AJAX web application where I load everything inside DIV elements the mouse positioning was always off when the container scrolled up or down.

This is also compatible with mobile browsers. I have tested it on iOS and Android browsers. It will detect a touch event or a mouse event based on the client. This was built to be unobtrusive but the only drawback is that you need jQuery to run this. You do not need to know anything about jQuery jus thow to include it.

The following is the HTML that you need to create 2 canvases. Place this in the body tag of your document.

What you need to make sure is that the ID of the container is pallete_"CANVASID", the ID of the canvas element itself should be the CANVASID and when the object is created it needs to be with CANVASID.
Now for the Javascript:
jQuery is only used to get the position of the cursor in this function getCoords(e)
I had previously used this function but it does not work if the container is scrollable.

Canvas is a very powerful element with a huge potential and I cannot wait for the day that we will reminisce and say "Remember that really buggy application that drove everyone crazy? It did not work on Linux, Mac and had so many security issues in Windows....What was it called? Ah, yes Flash."

My Blog List