Sierpinski Triangle d3.js demo
Built with blockbuilder.org
More demos: bl.ocks.org/jonyrock
Follow me on twitter: twitter.com/corpglory
license: mit |
Sierpinski Triangle d3.js demo
Built with blockbuilder.org
More demos: bl.ocks.org/jonyrock
Follow me on twitter: twitter.com/corpglory
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> | |
<style> | |
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } | |
</style> | |
</head> | |
<body> | |
<div class="svgHolder" id="svgHolder"> | |
<br> | |
<svg> | |
</svg> | |
</div> | |
<div class="row" style="width: 300px; margin:auto"> | |
<table style="width:100%"> | |
<tr> | |
<td style="width:100px">Level: <span id="levelLabel"> 1 </span></td> | |
</tr> | |
</table> | |
<input style="width:100%" type="range" id="levelRange" value="4" min="0" max="8" | |
step="1" oninput="onLevelChange()" | |
> | |
</div> | |
<script> | |
var width = 960; | |
var height = 400; | |
var fillColor = '#aaa' | |
var strokeColor = 'black'; | |
var sq32 = Math.sqrt(3) / 2; | |
var svg = d3.select("#svgHolder svg") | |
.attr("width", width) | |
.attr("height", height) | |
function add(posa, posb) { | |
return [posa[0] + posb[0], posa[1] + posb[1]]; | |
} | |
function drawSierpinski(selection, a, pos, level, maxLevel) { | |
if(level > maxLevel) { | |
return; | |
} | |
function getTrPathPoints(sk) { | |
return [[a / 2 * sk, sq32 * a * sk], [-a / 2 * sk, sq32 * a * sk]]; | |
} | |
function getTrPath() { | |
var pnts = getTrPathPoints(1); | |
var trianglePath = d3.path(); | |
trianglePath.moveTo(0, 0); | |
trianglePath.lineTo(pnts[0][0], pnts[0][1]); | |
trianglePath.lineTo(pnts[1][0], pnts[1][1]); | |
trianglePath.closePath(); | |
return trianglePath.toString(); | |
} | |
var g = selection.append('g'); | |
if(level == maxLevel) { | |
g | |
.append('path') | |
.attr("d", getTrPath()) | |
.attr("fill", fillColor) | |
var transform = 'translate(' + pos[0] + ',' + pos[1] + ')'; | |
g.attr('transform', transform) | |
} | |
var pnts = getTrPathPoints(0.5); | |
drawSierpinski(selection, a/2, pos, level + 1, maxLevel); | |
drawSierpinski(selection, a/2, add(pos, pnts[0]), level + 1, maxLevel); | |
drawSierpinski(selection, a/2, add(pos, pnts[1]), level + 1, maxLevel); | |
} | |
var sierpinskiGroup = undefined; | |
function onLevelChange() { | |
var val = $('#levelRange').val(); | |
$('#levelLabel').text(val); | |
if(sierpinskiGroup) { | |
sierpinskiGroup.remove(); | |
} | |
sierpinskiGroup = svg | |
.append('g') | |
.call(drawSierpinski, height, [width / 2, 0], 0, +val) | |
} | |
onLevelChange(); | |
</script> | |
</body> |