SVG Doodler IV
Draws a simple freehand line 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
var oO = {
//SVG namespace
ns: 'http://www.w3.org/2000/svg',
//Keeps track of the current object we are drawing
currentObj : null,
//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) {
var newpath = oO.currentObj.getAttribute('d') + ' ';
oO.currentObj.setAttribute('d', newpath);
oO.currentObj = null;
}
},
//Fired about a hundred times a second, draws random color/size circles
drawLine: function () {
var newpath = oO.currentObj.getAttribute('d') + ' L' + oO.currentpos.x + ',' + oO.currentpos.y;
oO.currentObj.setAttribute('d', newpath);
}
};
$(function () {
oO.cont = document.getElementById('cont');
oO.docbody = document.getElementsByTagName('body')[0];
//Fixed div for debugging
oO.debug = document.getElementById('debug');
//Track whether the mouse button is depressed or not.
oO.mouseDown = 0;
oO.docbody.onmousedown = function () {
oO.mouseDown = 1;
$(oO.debug).css('background-color', 'palegoldenrod')
};
...