SVG Doodler III
Draws random size/color circles onmousemove across a dynamically-generated SVG.
by djwelsh
HTML
<div id="djw-cont">
<div id="djw-controls"></div>
<div id="djw-canvas"></div>
<div id="djw-cover"></div>
</div>
<div id="djw-debug"></div>
CSS
#djw-debug {
position: fixed;
width: 500px;
height: 50px;
bottom: 0px auto;
left: 0px;
}
#djw-cont {
position: relative;
width: 500px;
height: 400px;
margin: 10px auto;
outline: 1px dashed #ccc;
}
#djw-controls {
position: absolute;
width: 50px;
height: 400px;
top: 0px;
left: 0px;
background-color: #eee;
}
#djw-canvas {
position: absolute;
width: 450px;
height: 400px;
top: 0px;
left: 50px;
background-color: whitesmoke;
}
#djw-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',
//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;
},
//Fired about a hundred times a second, draws random color/size circles
drawSprinkles: function () {
//Create requires namespace, but setting attributes does not.
var circ1 = document.createElementNS(oO.ns, 'circle');
circ1.setAttribute('cx', oO.currentpos.x);
circ1.setAttribute('cy', oO.currentpos.y);
circ1.setAttribute('r', Math.ceil(10 * Math.random()));
circ1.setAttribute('stroke', "#000000");
circ1.setAttribute('stroke-opacity', "0");
circ1.setAttribute('stroke-width', "1");
var rgbval = "rgb(" +
Math.floor(255 * Math.random()) + "," +
Math.floor(255 * Math.random()) + "," +
Math.floor(255 * Math.random()) + ")";
circ1.setAttribute('fill', rgbval);
oO.svg.appendChild(circ1);
}
};
$(function () {
oO.cont = document.getElementById('djw-cont');
oO.docbody = $(oO.cont).closest('body')[0];
//Fixed div for debugging
oO.debug =...