window.onload = function() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
canvas.addEventListener('mousemove', handleMove);
canvas.addEventListener('mousedown', handleDown);
canvas.addEventListener('mouseup', handleUp);
canvas.addEventListener("touchstart", handleStart, false);
canvas.addEventListener("touchend", handleEnd, false);
canvas.addEventListener("touchcancel", handleCancel, false);
canvas.addEventListener("touchleave", handleEnd, false);
canvas.addEventListener("touchmove", handleTouchMove, false);
xPos = e.clientX-canvas.offsetLeft;
yPos = e.clientY-canvas.offsetTop;
function handleStart(evt)
var touches = evt.changedTouches;
for(var i = 0; i < touches.length; i++)
if(isValidTouch(touches[i]))
arr_touches.push(copyTouch(touches[i]));
function handleTouchMove(evt)
var touches = evt.changedTouches;
var offset = findPos(canvas);
for (var i = 0; i < touches.length; i++)
if(isValidTouch(touches[i]))
var idx = ongoingTouchIndexById(touches[i].identifier);
ctx.moveTo(arr_touches[idx].clientX-offset.x, arr_touches[idx].clientY-offset.y);
ctx.lineTo(touches[i].clientX-offset.x, touches[i].clientY-offset.y);
arr_touches.splice(idx, 1, copyTouch(touches[i]));
var touches = evt.changedTouches;
var offset = findPos(canvas);
for (var i = 0; i < touches.length; i++)
if(isValidTouch(touches[i]))
var idx = ongoingTouchIndexById(touches[i].identifier);
ctx.moveTo(arr_touches[idx].clientX-offset.x, arr_touches[idx].clientY-offset.y);
ctx.lineTo(touches[i].clientX-offset.x, touches[i].clientY-offset.y);
arr_touches.splice(i, 1);
function handleCancel(evt)
var touches = evt.changedTouches;
for (var i = 0; i < touches.length; i++) {
arr_touches.splice(i, 1);
function copyTouch(touch)
return {identifier: touch.identifier,clientX: touch.clientX,clientY: touch.clientY};
function ongoingTouchIndexById(idToFind)
for (var i = 0; i < arr_touches.length; i++) {
var id = arr_touches[i].identifier;
function changeColor(new_color)
ctx.clearRect(0, 0, canvas.width, canvas.height);
function isValidTouch(touch)
var curleft = 0, curtop = 0;
if (canvas.offsetParent) {
curleft += canvas.offsetLeft;
curtop += canvas.offsetTop;
} while (touch == canvas.offsetParent);
offset = { x: curleft-document.body.scrollLeft, y: curtop-document.body.scrollTop };
if(touch.clientX-offset.x > 0 &&
touch.clientX-offset.x < parseFloat(canvas.width) &&
touch.clientY-offset.y >0 &&
touch.clientY-offset.y < parseFloat(canvas.height)) {
var curleft = 0, curtop = 0;
curleft += obj.offsetLeft;
} while (obj == obj.offsetParent);
return { x: curleft-document.body.scrollLeft, y: curtop-document.body.scrollTop };