An updated version of this post and demo is available here: http://www.kinderas.com/technology/2014/3/13/a-drawing-application
The web is no longer exclusive for desktop and laptop computers. With the introduction of the iPhone and the iPad Apple changed how we interact with the web. In the wake of Apples success with iOS devices we see the emergence of a slew of "handheld" devices. They are all different, some are small, others bigger and more powerful, however most of them utilize touch as a means of input. In this article I take a look at how we can create a simple touch enabled drawing application using only JavaScript and a tinsy-winsy bit of HTML 5.
First, you can try the finished app (with comments) and download the source code from here.
The first thing we need to do is to make sure that the user visiting our web-app is on a device which can understand touch events. This is pretty straight forward. We accomplish this by asking the «window» DOM element if is knows about one of the touch events.
if('ontouchstart' in window == false){
alert('Sorry, you need a touch enabled device to use this app');
return;
}
Now to the construction part. We need to create a canvas element.
var canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
ctx.strokeStyle = "rgba(255,0,0,1)";
ctx.lineWidth = 5;
ctx.lineCap = 'round';
In order for our fingers to be able to produce wonderful line drawings, we need to tell our application to listen for touch events. We'll need three of them. The «touchstart» event is where we set our starting position for the drawing operation. This event fires when a finger is added to the screen. The «touchmove» is where we draw the lines, this event fires when we move a finger on the screen. The «touchcancel» is where we handle exceptions, like what happens if you receive a call in the middle of your art creation extravaganza. This event fires whenever it needs to.
canvas.addEventListener("touchstart",touchstartHandler,false);
canvas.addEventListener("touchmove", touchmoveHandler,false);
canvas.addEventListener("touchcancel", touchcancelHandler,false);
Now we'll need to handle those events as well, here is where the real fun begins! Let's have a look a the «touchstart» handler first.
function touchstartHandler(event)
{
ctx.moveTo(event.touches[0].pageX, event.touches[0].pageY);
}
function touchmoveHandler(event)
{
ctx.lineTo(event.touches[0].pageX, event.touches[0].pageY);
ctx.stroke();
}
That's it. Try it out on your iPad, iPhone or any other touch device which understands the new HTML 5 APIs by clicking this magical link.
Recommended further reading: