HTML5 Canvas Paint App for iPhone

While working on a project I created this simple HTML5 Canvas Paint application for mobile touch devices. It runs on mobile safari (iOS touch devices) and also runs on android devices, since both have web-kit browsers. The code is very simple. JavaScript touch events have been used to listen to user’s touch movements on the screen and then the co-ordinates of the move are recorded for drawing. Also I have a clear button to clear everything on the Canvas and redraw. No multiple color support for drawing is there in the app as of now. You can see a screenshot of the app below, ignore my drawing though, it’s too bad. After the screenshot, the full code is provided.

Click to open the demo.

Full Code

<!DOCTYPE html>
<html>
<head>
<title>HTML5 Canvas Paint App - Mobile Web</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<style type="text/css">
body
{
  margin:20px;
  padding:0;
}
#paintBox
{
  border:1px solid #9a9a9a;
  width:100%;
}
</style>
<script type="text/javascript">
  var canvas = null; //canvas object
  var context = null; //canvas's context object
  var clearBtn = null; //clear button object

  /*boolean var to check if the touchstart event
  is caused and then record the initial co-ordinate*/
  var buttonDown = false;

  //onLoad event register
  window.addEventListener('load', initApp, false);

  function initApp() {
    setTimeout(function() { window.scrollTo(0, 1); }, 10); //hide the address bar of the browser.
    canvas = document.getElementById('paintBox');
    clearBtn = document.getElementById('clearBtn');

    setCanvasDmiension();
    initializeEvents();

    context = canvas.getContext('2d'); //get the 2D drawing context of the canvas
}

function setCanvasDmiension() {
  //canvas.width = 300; //window.innerWidth;
  canvas.height = window.innerHeight; //setting the height of the canvas
}

function initializeEvents() {
  canvas.addEventListener('touchstart', startPaint, false);
  canvas.addEventListener('touchmove', continuePaint, false);
  canvas.addEventListener('touchend', stopPaint, false);

  clearBtn.addEventListener('touchend', clearCanvas,false);
}

function clearCanvas() {
  context.clearRect(0,0,canvas.width,canvas.height);
}

function startPaint(evt) {
  if(!buttonDown)
  {
    context.beginPath();
    context.moveTo(evt.touches[0].pageX, evt.touches[0].pageY);
    buttonDown = true;
  }
  evt.preventDefault();
}

function continuePaint(evt) {
  if(buttonDown)
  {
    context.lineTo(evt.touches[0].pageX,evt.touches[0].pageY);
    context.stroke();
  }
}

function stopPaint() {
  buttonDown = false;
}
</script>
</head>
<body>
  <p><input type="button" value="Clear" id="clearBtn"/></p>
  <canvas id="paintBox">
    Your browser doesnot support canvas
  </canvas>
</body>
</html>

Details

I have put together the CSS and JavaScript code in the HTML file itself. As always you can separate them and it will still work. Ok, lets talk about the details of the code.

As you can see, below the <title>, we have a meta tag. This one is specifically for mobile web-kit browsers (the ones in iPhones and Android devices), that means the desktop browsers would not understand it. The meta tag tells the browser that the scaling of the application should be as per the device’s width. Also the  initial-scale=1.0 and user-scalable=noensures that, you cannot scale the application manually, that is you cannot zoom in using pinch-to-zoom gesture. Then comes the CSS, which is pretty simple, so lets not talk about it. Lets come to the HTML now,

<body>
  <p><input type="button" value="Clear" id="clearBtn"/></p>
  <canvas id="paintBox">
    Your browser doesnot support canvas
  </canvas>
</body>

The HTML block is also very simple. We have a HTML5 Canvas and a push button for clearing the drawings on the canvas. You can see a message “Your browser doesnot support canvas” inside the <canvas> tag. Now, if your browser doesn’t support HTML5 canvas, then this message would be displayed.

Lets check out the java script now. At most places I have added comments for clarity. The code itself is also very simple. It starts with a window onLoad event handler function, inside which we initialize the app. The first line inside initApp() method, scrolls the window vertically so as to hide the address bar (URL bar) of the browser, which gives the app more of a native look. This is a very nice hack to auto hide the address bar. Then we have defined methods for setting the canvas height (setCanvasDmiension()) and also to initialize all the user events (initializeEvents()), which will register the necessary touch based javascript events for drawing. Lets move to the initializeEvents method. The code block is below,

function initializeEvents() {
  canvas.addEventListener('touchstart', startPaint, false);
  canvas.addEventListener('touchmove', continuePaint, false);
  canvas.addEventListener('touchend', stopPaint, false);

  clearBtn.addEventListener('touchend', clearCanvas,false);
}

As you can see we have touch based javascript events. These are standard javascript DOM events for web kit based browsers. As you might have guessed it right, touchstart is the equivalent of mousedown, touchmove for mousemove and touchend for mouseup. Since a mobile device doesnot have a mouse to interact, hence the touch events were introduced to give a fluidity to the interaction behavior. That does not mean that you cannot use the mouse events for a touch device. You can still use the standard mouse events such as click, mousedown, mouseup e.t.c. We have registered the three standard touch events for our canvas, and upon generation of the events necessary functions are called to handle it. We also have registered a touchend event to the clear button, so that when you tap it clearCanvas() method is called to clear out the canvas.

Thereafter, we have the event handler methods for capturing the touch co-ordinates and drawing.

function startPaint(evt) {
  if(!buttonDown)
  {
    context.beginPath();
    context.moveTo(evt.touches[0].pageX, evt.touches[0].pageY);
    buttonDown = true;
  }
  evt.preventDefault();
}

function continuePaint(evt) {
  if(buttonDown)
  {
    context.lineTo(evt.touches[0].pageX,evt.touches[0].pageY);
    context.stroke();
  }
}

As you can see above, startPaint() is called when touchstart event is fired. Inside it, we move the drawing cursor to the point where your finger touched the mobile screen. And then evt.preventDefault(); prevents the web page from being dragged around the browser, which is the default behavior when you finger taps the screen and moves around. So, we are preventing the drag behavior so that you can draw inside the canvas. continuePaint() is called when touchmove is fired, i.e when you move your finger. Inside this function we just draw the line to the point where your finger has moved to at present and then continue to draw the line as you move your finger along the canvas, by getting the latest co-ordinates. The co-ordinates of the finger is stored in the event(evt in our case) object’s touches array. The touches array stores the co-ordinates of multiple fingers touching the screen. Since our application is a single touch application so we get the co-ordinates from the zeroth index of the array i.e touches[0]. Now, each finger co-ordinates can be accessed from the pageX and pageY property. And then finally we have context.stroke() to pen down the line we have drawn (i.e draw it actually on the screen).

Finally, we have the stopPaint() function which is called when your finger is withdrawn from the screen.

The overall application is pretty simple to build, but can be scaled. We can add multiple color support to the app to fill up the drawing and also to give a stroke color.  Here is the link to the demo

http://jbk404.site50.net/html5/paint/

Open the app in a touch device as it will not work on a desktop browser, since we have touch events.

About these ads

3 thoughts on “HTML5 Canvas Paint App for iPhone

  1. Good post. I study something more difficult on totally different blogs everyday. It would always be stimulating to learn content material from other writers and observe slightly something from their store. I want to make use of some with the content material on my blog whether you don’t mind. Natually I provide you with a hyperlink in your net blog. Thanks for sharing.

  2. Pingback: Simple HTML5 Canvas Drawing App: ‘Stache the Hipster | Delmar Senties: Alt. Media Design

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s