Last active
October 31, 2017 11:42
-
-
Save johnwalley/6392ed3100847cc757ff57786cfe116c to your computer and use it in GitHub Desktop.
Sierpinski triangle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<style> | |
body { | |
background: #202020; | |
margin: 0px; | |
padding: 0px; | |
} | |
p { | |
position: absolute; | |
font-family: Open Sans, sans-serif; | |
font-size: 24px; | |
color: white; | |
margin: 20px; | |
} | |
</style> | |
<p id="instruction1">Click or press three times to create a triangle</p> | |
<p id="instruction2">Now choose a starting point</p> | |
<canvas id="canvas"></canvas> | |
<script> | |
var canvas = document.getElementById("canvas"); | |
canvas.width = window.innerWidth; | |
canvas.height = window.innerHeight; | |
var ctx = canvas.getContext("2d"); | |
var numClicks = 0; | |
var points = []; | |
document.getElementById("instruction2").style.display = "none"; | |
canvas.addEventListener( | |
"mousedown", | |
function(event) { | |
var x = event.x; | |
var y = event.y; | |
if (numClicks < 3) { | |
ctx.fillStyle = 'rgba(247, 183, 51, 1)'; | |
drawPoint(x, y, 5); | |
points[numClicks] = [x, y]; | |
if (numClicks === 2) { | |
document.getElementById("instruction1").style.display = "none"; | |
document.getElementById("instruction2").style.display = "block"; | |
} | |
numClicks++; | |
} else { | |
document.getElementById("instruction2").style.display = "none"; | |
ctx.fillStyle = 'rgba(252, 74, 26, 1)'; | |
drawPoint(x, y, 5); | |
ctx.fillStyle = "rgba(74, 189, 172, 0.7)"; | |
draw(x, y); | |
} | |
}, | |
false | |
); | |
ctx.fillStyle = "deepskyblue"; | |
function draw(x, y) { | |
var point = points[Math.floor(Math.random() * 3)]; | |
var newPoint = [x + (point[0] - x) / 2, y + (point[1] - y) / 2]; | |
drawPoint(newPoint[0], newPoint[1]); | |
requestAnimationFrame(function() { | |
draw(newPoint[0], newPoint[1]); | |
}); | |
} | |
function drawPoint(x, y, r = 2) { | |
ctx.beginPath(); | |
ctx.arc(x, y, r, 0, 2 * Math.PI); | |
ctx.fill(); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment