SVG Doodler V

Draws a simple rectangle onmousemove across a dynamically-generated SVG.

by djwelsh

HTML

<div id="cont">
    <div id="controls"></div>
    <div id="canvas"></div>
    <div id="cover"></div>
</div>
<div id="debug"></div>

CSS

#debug {
    position: fixed;
    width: 500px;
    height: 50px;
    bottom: 0px auto;
    left: 0px;
}
#cont {
    position: relative;
    width: 500px;
    height: 400px;
    margin: 10px auto;
    outline: 1px dashed #ccc;
}
#controls {
    position: absolute;
    width: 50px;
    height: 400px;
    top: 0px;
    left: 0px;
    background-color: #eee;
}
#canvas {
    position: absolute;
    width: 450px;
    height: 400px;
    top: 0px;
    left: 50px;
    background-color: whitesmoke;
}
#cover {
    position: absolute;
    width: 450px;
    height: 400px;
    top: 0px;
    left: 50px;
    background-color: transparent;
    background-image: url('http://www.davidjohnwelsh.com/img/clearbg.png');
    cursor: crosshair;
}

JavaScript

//dev - need to allow drawing in negative directions!

var oO = {
    //SVG namespace
    ns: 'http://www.w3.org/2000/svg',
    
    //Keeps track of the current object we are drawing
    currentObj : null,
    currentObjVals : {
        x : 0,
        y : 0,
        width : 0,
        height : 0
    },
    
    //Elements on page
    cont: null,
    docbody: null,
    svg: null,
    canvas: null,
    cover: null,

    //Adjustment of mouse position depending on window size, margins etc.
    offsetX: 0,
    offsetY: 0,
    getOffset: function (foo) {
        var curleft = 0;
        var curtop = 0;

        for (var obj = foo; obj !== null; obj = obj.offsetParent) {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;

        }
        oO.offsetX = curleft;
        oO.offsetY = curtop;

    },

    //Current mouse position relative to the #canvas
    currentpos: {
        x: 0,
        y: 0
    },

    //Boolean to determine whether to convert mouse movement to drawing or not
    drawing: false,
    //Stores the Interval we use while drawing
    drawping: null,
    killDrawing: function () {
        oO.drawing = false;
        clearInterval(oO.drawping);
        oO.drawping = null;
        if (oO.currentObj) {
            oO.currentObj = null;
        }
    },

    //Fired about a hundred times a second, draws random color/size circles
    drawLine: function () {
        
        var x0 = 0;
        var y0 = 0;
        var x1 = Math.abs(oO.currentObjVals.width);
        var y1 = Math.abs(oO.currentObjVals.height);
        
        if (oO.currentObjVals.width < 0) {
            x0 = oO.currentObjVals.x + oO.currentObjVals.width;
        }
        else {
            x0 = oO.currentObjVals.x;
        }
        
        if (oO.currentObjVals.height < 0) {
            y0 = oO.currentObjVals.y + oO.currentObjVals.height;
        }
        else {
            y0 = oO.currentObjVals.y;
        }
        
        
       ...