Skip to content

Instantly share code, notes, and snippets.

@ikr7 ikr7/index.html
Created Dec 10, 2018

Embed
What would you like to do?
Synchronization Phenomena
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Boid Simulation</title>
<style media="screen">
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
position: relative;
background: black;
}
canvas {
/* background: #def; */
}
form {
position: absolute;
top: 1em;
left: 1em;
}
</style>
</head>
<body>
<canvas></canvas>
<form>
<!-- <input type="button" id="a" value="aiueo"> -->
</form>
<script>
const $ = document.querySelector.bind(document);
const width = 960;
const height = 500;
const canvas = $('canvas');
const context = canvas.getContext('2d');
document.body.style.width = width;
document.body.style.height = height;
canvas.width = width;
canvas.height = height;
context.fillStyle = 'white';
context.lineWidth = 3;
let N = 128;
let pendulums = [];
for (let i = 0; i < N; i++) {
pendulums[i] = {
ang: Math.random() * 2 * Math.PI,
angv: 0.025 + 0.0125 * Math.random()
};
}
function draw () {
// context.fillStyle = 'rgba(255, 255, 255, 0.66)';
// context.fillRect(0, 0, width, height);
// context.fillStyle = 'rgba(0, 0, 0, 1.0)';
context.clearRect(0, 0, width, height);
context.beginPath();
context.arc(width / 2, height / 2, 230, 0, Math.PI * 2, false);
context.closePath();
context.strokeStyle = 'white';
context.stroke();
context.strokeStyle = 'black';
pendulums.forEach((p) => {
context.beginPath();
context.arc(230 * Math.cos(p.ang) + width / 2, 230 * Math.sin(p.ang) + height / 2, 10, 0, Math.PI * 2, false);
context.closePath();
context.fill();
context.stroke();
});
}
function step () {
const eps = 0.01;
let p = [];
for (let i = 0; i < N; i++) {
let sync = 0;
for (let j = 0; j < N; j++) {
sync += Math.sin(pendulums[j].ang - pendulums[i].ang);
}
p[i] = {
ang: pendulums[i].ang + pendulums[i].angv + eps * sync / N,
angv: pendulums[i].angv
};
}
pendulums = p;
}
(function animate () {
draw();
step();
setTimeout(animate, 1000 / 30);
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.