css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <canvas id="canvas"></canvas>
            
          
!
            
              body {
  background-color: black;
  color: white;
  display: flex;
  align-items: center;
  flex-direction: column;
  margin: 0;
}
            
          
!
            
              var params = {
  fps: 60,
  clear: false,
  splitDistance: 30,
  attract: 3,
  repel: 1,
  repelNeighbors: 10,
  noise: 3,
  stepScale: 1,
  nPoints: 8,
}

// I'm a fool for rolling my own vector library here.
function vectorAdd(p1, p2) {
  return {x: p1.x + p2.x, y: p1.y + p2.y};
}
function vectorScale(p, s) {
  return {x: p.x*s, y: p.y*s};
}
function vectorSub(p1, p2) {
  return {
    x: p1.x - p2.x,
    y: p1.y - p2.y,
  }
}
function dot(p1, p2) {
  return p1.x * p2.x + p1.y + p2.y;
}
function norm(p) {
  return distance(p, {x:0, y:0});
}
function normalize(p) {
  var n = norm(p)
  return {
    x: p.x / n,
    y: p.y / n
  }
}

function initCircle(n, r, canvas) {
  var points = [];
  for (var i = 0; i < n; i++) {
    var theta = 2 * Math.PI * i/n;
    points.push({
      x: canvas.width/2 + r * Math.cos(theta),
      y: canvas.height/2 + r * Math.sin(theta),
    })
  }
  return points;
}


var c = document.getElementById("canvas");
c.width = window.innerWidth;
c.height = window.innerHeight;
var ctx = c.getContext("2d");
ctx.strokeStyle = "rgba(255,255,255,.1)";
ctx.fillStyle = "white";
var previous_time = 0;

var points;
params.restart = function(){
  ctx.clearRect(0,0,c.width,c.height);
  points = initCircle(params.nPoints, 40, c);
};
params.restart();

function distance(a, b){
  return Math.sqrt(Math.pow(a.x - b.x, 2) +  Math.pow(a.y - b.y, 2));
}

function draw(points) {
  var tree = new kdTree(points, distance, ["x", "y"]);
  points.forEach(function(p) {
    ctx.fillRect(p.x, p.y, 1, 1);
    var nearest = tree.nearest(p, 3);
    nearest.forEach(function(p2) {
      if (p2[1] !== 0) {
        ctx.beginPath();
        ctx.moveTo(p.x, p.y);
        ctx.lineTo(p2[0].x, p2[0].y);
        ctx.stroke();
      }
    })
  })
}

function split(points) {
  var tree = new kdTree(points, distance, ["x", "y"]);
  var newPoints = [];
  points.forEach(function(p) {
    var nearest = tree.nearest(p, 3);
    nearest.forEach(function(p2) {
      var theta = Math.acos(dot(p2[0], p) / (norm(p) * norm(p2[0])))
      // We can use theta to change the probability with the curvature.
      if (p2[1] > params.splitDistance) {
        newPoints.push({
          x: (p2[0].x + p.x)/2,
          y: (p2[0].y + p.y)/2
        });
      }
    });
  });
  // Filter duplicates
  var uniqueSplits = [];
  for(var i = 0; i < newPoints.length; i++) {
    var dupe = false;
    for(var j = i+1; j < newPoints.length; j++) {
      dupe = dupe || (newPoints[i].x == newPoints[j].x && newPoints[i].y == newPoints[j].y)
    }
    if (!dupe) {
      uniqueSplits.push(newPoints[i]);
    }
  }
  return uniqueSplits;
}

function move(points) {
  var tree = new kdTree(points, distance, ["x", "y"]);
  var newPoints = [];
  return points.map(function(p) {
    var nearest = tree.nearest(p, 10).sort(function(p1,p2) {
      if (p1[1] === p2[1]) {return 0;}
      return p1[1] < p2[1] ? -1 : 1;
    });
    var towards = nearest.slice(1,3).map(function(N) {
      var p2 = N[0];
      // Attraction should have magnitude that grows superlinearly and drops off at close distances.
      var s = norm(vectorSub(p2, p)) < 20 ? 1 : 1.5;
      return vectorScale(normalize(vectorSub(p2, p)), s);
    }).reduce(vectorAdd, {x:0,y:0});
    var repel = nearest.slice(3, 3 + params.repelNeighbors).map(function(N) {
      var p2 = N[0];
      return normalize(vectorSub(p2, p));
    }).reduce(vectorAdd, {x:0,y:0});
    var noise = {
      x: (Math.random() - .5) * params.noise, 
      y: (Math.random() - .5) * params.noise
    };
    var forces = vectorAdd(vectorScale(towards, params.attract), vectorScale(repel, -params.repel));
    return vectorAdd(p, vectorScale(vectorAdd(noise, forces), params.stepScale));
  });
}

points = points.concat(split(points));

points = move(points);
draw(points);



function update() {
  var time = (new Date()).getTime()/1000;
  if (time - previous_time > 1/params.fps) {
    previous_time = time;
    points = points.concat(split(points));
    points = move(points);
    params.clear ?ctx.clearRect(0,0,c.width,c.height) : 0;
    draw(points);
  }
  window.requestAnimationFrame(update);
}

var gui = new dat.GUI();
gui.add(params, "fps", 1, 60);
gui.add(params, "restart");
gui.add(params, "clear");

gui.add(params, "splitDistance", 1, 100);
gui.add(params, "attract", 0, 10);
gui.add(params, "repel", 0, 10);
gui.add(params, "repelNeighbors", 0, 20);
gui.add(params, "noise", 0, 20);
gui.add(params, "stepScale", 0, 1);
gui.add(params, "nPoints", 3, 100).step(1);

update();

// Notes: we probably want to repel if things are too close together. This will hopefully end the degenerate bunching that happens and make it more stable.

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console