Touch Safe doodling using Raphael

by veeramarni

HTML

<div id="canvas" style="width:500px; height:500px;"></div>
<button id="clear-canvas">Clear</button>

CSS

body {
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -o-user-select: none;
    user-select: none;
}

JavaScript

Raphael("canvas", function () {
    var win = Raphael._g.win,
        doc = win.document,
        hasTouch = "createTouch" in doc,
        
        M = "M",
        L = "L",
        d = "d",
        COMMA = ",",
        // constant for waiting doodle stop
        INTERRUPT_TIMEOUT_MS = hasTouch ? 100 : 1,
        // offset for better visual accuracy
        CURSOR_OFFSET = hasTouch ? 0 : -10,
        
        paper = this,
        path = "", // hold doodle path commands
        // this element draws the doodle
        doodle = paper.path(path).attr({
            "stroke": "rgb(200,100,50)"
        }),
        
        // this is to capture mouse movements
        tracker = paper.rect(0, 0, paper.width, paper.height).attr({
            "fill": "rgb(255,255,255)",
            "fill-opacity": "0.01"
        }),
        active = false, // flag to check active doodling
        repath = false, // flag to check if a new segment starts
        interrupt; // this is to connect jittery touch
    
    tracker.mousedown(function () {
        interrupt && (interrupt = clearTimeout(interrupt));
        active = true;
        repath = true;
    });
    
    Raphael.mousemove(function (e, x, y) {
        // do nothing if doodling is inactive
        if (!active) {
            return;
        }
        
        // Fix for Raphael's touch xy bug
        if (hasTouch && 
                (e.originalEvent.targetTouches.length === 1)) {
            x = e.clientX + 
                (doc.documentElement.scrollTop || doc.body.scrollTop || 0);
            y = e.clientY + 
                (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0);
            e.preventDefault();
        }
        
        // Insert move command for a new segment
        if (repath) {
            path += M + (x + CURSOR_OFFSET) + COMMA + 
                    (y + CURSOR_OFFSET);
            repath = false;
        }
        path += L + (x + CURSOR_OFFSET) + COMMA + 
                (y + CURSOR_OFFSET); //...