Sketch Pad using touch and canvas

This sample app demonstrates how to use touch events to draw free hand sketch/drawing on the canvas. It demonstrates the usage of html5 canvas.

Using the application:

The example application screen shot

  • The two items on top with small and big circle can be used to change the brush size.
  • Clear button is used to clear the canvas.
  • Red and Black square can be clicked to change the brush color.
  • The selected color and brush size are highlighted.
  • Use the back button on footer to exit the application.

Create canvas

The canvas is defined in the index.html file:

<div id="canvas"></div>

Get the canvas and get the 2d context:

//Create a canvas that covers the entire screen
canvas = document.createElement('canvas');
canvas.height = screen.availHeight;
canvas.width = screen.availWidth;
ctx = canvas.getContext("2d");

Add touch event listener to the document to receive user events:

document.addEventListener("touchstart", onTouchStart, false);
document.addEventListener("touchmove", onTouchMove, false);
document.addEventListener("touchend", onTouchEnd, false);
document.addEventListener("touchcancel", onTouchCancel, false);

Here the first argument e.g. “touchstart” is the system event which will call the user defined function onTouchStart.

Now once the user touches/moves finger on the phone screen respective event will be generated. You need to handle the events and accordingly draw the line. For e.g. the following snippet shows the drawOnTouchMove(x, y) function.

function onTouchMove(event)

	var touchEvent, x, y;

	touchEvent = event.changedTouches[0];
	x = touchEvent.pageX;
	y = touchEvent.pageY;

	drawOnTouchMove(x, y);

function drawOnTouchMove(x, y)
	if (isWithinPanelBound(y))
		prev_x = -1;
		prev_y = -1;
	if (x || y)
		if ((prev_x === -1) || prev_y === -1)
			prev_x = x;
			prev_y = y;
		drawLine(x, y);
		prev_x = x;
		prev_y = y;

In the above code preventDefault methods prevents the default behavior of browser and allows to draw .prev_x and prev_y are the previous touch position, the function isWithinPanelBound(y) checks if the touch has happened in the top panel area. The drawline(x, y) method draws the line. Check the main.js file in the attached sample application to see all the related functions and variables.

function drawLine(x, y) {
	ctx.lineWidth = brush_size;
	ctx.strokeStyle = current_color;
	ctx.moveTo(prev_x, prev_y);
	ctx.lineTo(x, y);

Here the variables brush_size and current_color are the user selected size and color for the brush. The line is drawn from x, y coordinates passed in function moveTo to the x, y coordinates passed in function lineTo.

Build Requirements:

The application is built for devices with Tizen 2.0 firmware.

SDK Environment used:  2.0.0a2


Sample app attached.

Revision History:

Description Date
First version December 14, 2012
File attachments: