Lightning v2(veins)
canvas vein generation
HTML
<body>
<div>
<canvas id="myCanvas" width="500" height="500"></canvas>
</div>
</body>
CSS
body {
margin: 0px;
padding: 0px;
background-color:black;
}
div { background-color:white; width:500px; height:500px }
JavaScript
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var width = 500;
var height = 500;
// note: with a maxCount of 3 the initial branch will be created plus two branches each with two branches. Totalling 7 points.
// initial branch call
genArm(width / 2,height, height / 4, 90, 0.24, 0, 5);
// Generate an arm and try and create two branches at the end
function genArm(pPointX, pPointY, pLength, pAngle, pAngleRange, count, maxCount) {
console.log('genArm '+count);
count += 1;
if (count >= maxCount) return; // no more branches to make
var length = (pLength * getRandomRange(0.2,1)); // this 10% may need to be tuned
var angle = pAngle // WTF! = (pAngle - pAngleRange) + (pAngleRange * 2) * getRandom();
var angleRad = deg2Rad(angle);
var x = pPointX + (0-length) * Math.cos(angleRad);
var y = pPointY + (0-length) * Math.sin(angleRad);
console.log('old length '+pLength);
console.log('new length '+length);
console.log('old angle '+pAngle);
console.log('new angle '+angle);
console.log('old point '+pPointX+', ' +pPointY);
console.log('new point '+x+', '+y);
context.save();
context.beginPath();
context.moveTo(pPointX, pPointY);
context.lineTo(x, y);
context.stroke();
context.restore();
// two new arms from this point
genArm(x, y, length, angle - (angle * getRandomRange(0.1,pAngleRange)), pAngleRange, count, maxCount);
genArm(x, y, length, angle + (angle * getRandomRange(0.1,pAngleRange)), pAngleRange, count, maxCount);
}
// return random value between 0 and 1.0
function getRandom() {
return Math.random();
}
// return random value between min and max
function getRandomRange(min,max) {
return min+( max * getRandom());
}
function deg2Rad(deg) {
return deg * Math.PI / 180;
}