Just a little trembling triangle.
Last active
April 27, 2017 23:47
-
-
Save veltman/838d79704281f45822d6320c8c2a4fd0 to your computer and use it in GitHub Desktop.
Trembling triangle
This file contains 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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" /> | |
</head> | |
<body> | |
<canvas width="960" height="500"></canvas> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script> | |
let context = document.querySelector("canvas").getContext("2d"), | |
interval = 45000, | |
triangle = [[480, 50], [680, 450], [280, 450]], | |
line = d3.line().context(context), | |
pixelScale = d3.scaleLinear() | |
.range([2, 8]), | |
depthScale = d3.scaleLinear() | |
.rangeRound([3, 7]), | |
offsetter; | |
context.globalAlpha = 0.1; | |
d3.timer(function(t){ | |
t = Math.min(t % interval / interval, 1 - t % interval / interval) * 2; | |
offsetter = d3.randomNormal(0, pixelScale(t)); | |
context.clearRect(0, 0, 960, 500); | |
context.fillStyle = d3.interpolateWarm(t / 2); | |
for (let i = 0; i < 10; i++) { | |
context.beginPath(); | |
line(tremble(triangle, depthScale(t))); | |
context.closePath(); | |
context.fill(); | |
} | |
}); | |
function tremble(shape, depth) { | |
return shape.reduce((newPoints, val, i) => { | |
return [...newPoints, val, ...getBetween(val, shape[i + 1] || shape[0], depth)]; | |
}, []); | |
} | |
function getBetween(a, b, depth) { | |
const midpoint = [ | |
a[0] + (b[0] - a[0]) * 0.5 + offsetter(), | |
a[1] + (b[1] - a[1]) * 0.5 + offsetter() | |
]; | |
if (depth === 1) { | |
return [midpoint]; | |
} | |
return [...getBetween(a, midpoint, depth - 1), midpoint, ...getBetween(midpoint, b, depth - 1)]; | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment