Pen Settings

HTML

CSS

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

JavaScript

Babel includes JSX processing.

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

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                #container
              
            
!

CSS

              
                document, body {
  margin: 0;
  min-height: 100vh;
}
body {
  align-items: center;
  display: flex;
  justify-content: center;
}

#container {
  align-items: center;
  display: flex;
  flex-direction: column;
}

button {
  max-width: 200px;
  margin-top: 10px;
}
              
            
!

JS

              
                import { SVG } from 'https://cdn.skypack.dev/@svgdotjs/svg.js'
import { Vec2 } from 'https://cdn.skypack.dev/wtc-math';
import fitCurve from 'https://cdn.skypack.dev/fit-curves';
console.clear();

const config = {
  seed: 1337,
  nscale: .005,
  sscale: 20,
  stepSize: 1,
  num: 1,
  r: 100,
  k: 30,
  numwalkers: 200,
  stagePadding: 40
};
const vars = {
  newPositions: [],
  activeList: [],
  fullList: [],
  walkers: [],
  grid: null,
  newPosition: null
}
let noise;

const dimensions = new Vec2(750, 500);

var drawing = SVG().addTo('#container').size(dimensions.x, dimensions.y);

 /// Create the download button
const dl = document.createElement('button');
dl.innerText = 'download';
dl.addEventListener('click', () => { 
   const fileName = "untitled.svg"
   const url = "data:image/svg+xml;utf8," + encodeURIComponent(drawing.svg());
   const link = document.createElement("a");
   link.download = fileName;
   link.href = url;
   link.click();
});
document.body.querySelector('#container').appendChild(dl);

let running;
const setup = () => {
  running = false;
  setTimeout(() => {
    running = true;
    vars.currentPosition = [];
    vars.activeList = [];

    config.num = Math.floor(floatRandomBetween(1, 5));
    config.num = 1;
    config.nscale = floatRandomBetween(.001, .05);
    config.sscale = floatRandomBetween(5, 50);
    config.seed = floatRandomBetween(0, 99999);
    
    config.nscale1 = floatRandomBetween(.001, .01);
    config.sscale1 = floatRandomBetween(.1, 1);

    noise = new SimplexNoise(config.seed);
    
    vars.stageHeight = dimensions.y + config.stagePadding * 2.;
    vars.stepsize = vars.stageHeight / config.numwalkers;
    vars.position = new Vec2(0,-config.stagePadding);
    
    config.r = floatRandomBetween(50, 200);

    const selectionPadding = 30;
    vars.grid = new Grid({ 
      size: dimensions.array,
      cellSize: config.r / Math.SQRT2,
      fill: -1
    });
    let pos;
    // const pos = new Vec2(
    //   floatRandomBetween(selectionPadding, dimensions.width-selectionPadding),
    //   floatRandomBetween(selectionPadding, dimensions.height-selectionPadding)
    // );
    while(true) {
      pos = new Vec2(
        floatRandomBetween(selectionPadding + 200, dimensions.width-selectionPadding),
        floatRandomBetween(selectionPadding, dimensions.height-selectionPadding)
      );
      const n = Math.max(noise.noise2D(pos.clone().scale(config.nscale).array) * 2, 0);
      if(n > .5) break;
    }
    vars.grid.addChildAtPosition(pos, pos);
    vars.activeList.push(pos);
    vars.newPositions.push(pos);

    drawing.clear();
    draw();
  }, 10);
};

class Grid {
  static #defaults = {
    size: dimensions.clone(),
    cellSize: new Vec2(50,50),
    fill: null
  };
  #grid = [];
  #size;
  #cellSize;
  
  constructor(settings) {
    settings = Object.assign({}, Grid.#defaults, settings);
    this.#size = Vec2.interpolate(settings.size) || Grid.#defaults.size;
    this.#cellSize = Vec2.interpolate(settings.cellSize) || Grid.#defaults.cellSize;
    this.#grid.length = this.gridSize.area;
    this.#grid.fill(settings.fill || Grid.#defaults.fill);
  }

  addChild(child, i) {
    this.#grid[i] = child;
  }
  addChildAtPosition(child, pos) {
    this.#grid[this.getArrayPosition(pos)] = child;
  }
  addChildAtGridPosition(child, gridPos) {
    this.#grid[this.getArrayPositionFromGridPos(gridPos)] = child;
  }

  getChild(i) {
    return this.#grid[i];
  }
  getChildAtPosition(pos) {
    return this.#grid[this.getArrayPosition(pos)];
  }
  getChildAtGridPosition(gridPos) {
    return this.#grid[this.getArrayPositionFromGridPos(gridPos)];
  }

  getGridPositionForIndex(i) {
    const gsize = this.gridSize;
    return new Vec2(i%gsize.x, Math.floor(i/gsize.x));
  }

  getArrayPositionFromGridPos(gpos) {
    const gsize = this.gridSize;
    if(
      gpos.x < 0 || gpos.x >= gsize.x ||
      gpos.y < 0 || gpos.y >= gsize.y )
      return null;
    
    gpos.x = gpos.x % gsize.x;
    const arraypos = (gpos.x) + (gpos.y*gsize.x);
    return arraypos;
  }

  getArrayPosition(realPos) {
    const gpos = this.getGridPos(realPos);
    return this.getArrayPositionFromGridPos(gpos);
  }

  getGridPos(realPos) {
    if(realPos instanceof Vec2) {
      return realPos.divideNew(this.#cellSize).floor();
    }
    // Throw an error
  }
  getSubPos(realPos) {
    if(realPos instanceof Vec2) {
      return realPos.modNew(this.#cellSize);
    }
    // Throw an error
  }
  getRealPos(gridPos) {
    if(gridPos instanceof Vec2) {
      return gridPos.multiplyNew(this.#cellSize);
    }
    // Throw an error
  }

  get size() {
    return this.#size;
  }
  get gridSize() {
    return this.#size.divideNew(this.#cellSize).floor();
  }
  get cellSize() {
    return this.#cellSize;
  }
  get length() {
    return this.#grid.length;
  }
}

class Body {
  constructor(pos, r) {
    this.pos = pos;
    this.r = r;
  }
}

class Walker {
  constructor(position) {
    this.position = position;
    this.angle = 0;
    this._points = [position];
    this.stepsize = 2;
  }
  walk() {
    this.angle = noise.noise2D(this.position.clone().scale(config.nscale1).array) * (config.sscale1);
    const diffPos = new Vec2(Math.cos(this.angle) * this.stepsize, Math.sin(this.angle) * this.stepsize);
    this.addPoint(this.position.addNew(diffPos));
  }
  addPoint(point) {
    this.position = point;
    this._points.push(point);
  }
  get points() {
    return this._points.map(p => p.array);
  }
  get bezier() {
    const bezierCurves = fitCurve(this.points, .1);
    let str = "";
    bezierCurves.map(function(bezier, i) {
      if (i == 0) {
          str += "M " + bezier[0][0] + " " + bezier[0][1];
      }
      str += "C " + bezier[1][0] + " " + bezier[1][1] + ", " +
          bezier[2][0] + " " + bezier[2][1] + ", " +
          bezier[3][0] + " " + bezier[3][1] + " ";
    });

    return str;
  }
}

const spiral = (pos, r, f, colour = '#f06') => {
  let _r = .01;
  let a = 0;
  const ps = [];
  const w = new Vec2( Math.cos(a)*_r, Math.sin(a)*_r );
  ps.push(w.clone());
  while(_r < r) {
    _r = w.length;
    const step = new Vec2(0, f*.5);
    step.angle = w.angle + Math.PI * .5;
    a = w.angle;
    w.add(step);
    ps.push(w.clone());
  }
  
  const bezierCurves = fitCurve(ps.map(p => p.addNew(pos).array), .1);
  let str = "";
  bezierCurves.map(function(bezier, i) {
    if (i == 0) {
        str += "M " + bezier[0][0] + " " + bezier[0][1];
    }
    str += "C " + bezier[1][0] + " " + bezier[1][1] + ", " +
        bezier[2][0] + " " + bezier[2][1] + ", " +
        bezier[3][0] + " " + bezier[3][1] + " ";
  });
  
  // drawing.polyline(ps.map(p => p.addNew(pos).array)).fill("none").stroke(colour); 
  drawing.path(str).fill("none").stroke(colour);
  drawing.circle(r*2.).fill("none").stroke(colour).move(pos.x-r, pos.y-r);
}


const drawStep = () => {
  if(!running) return;
  if(vars.newPositions.length > 0) {
    vars.newPositions.forEach(c => {
      const n = noise.noise2D(c.clone().scale(config.nscale).array);
      let r = Math.max(.0, n) * config.sscale;
      if(r > 0) {
        
        spiral(c, r, 1, '#06f');
        // let _r = r;
        // while(r > 1) {
        //   drawing.circle(r).fill("none").stroke('#06f').move(c.x-r*.5, c.y-r*.5);
        //   r -= 3;
        // }
        // drawing.circle(r).fill("none").stroke('#f06').move(c.x-r*.5, c.y-r*.5);

        // vars.fullList.push(new Body(c, r));
        vars.grid.addChildAtPosition(new Body(c, r*2), c);
      }
    });
  }
  vars.newPositions = [];
  if(vars.activeList.length > 0) {
    const ri = Math.floor(0, floatRandomBetween(vars.activeList.length));
    const c = vars.activeList[ri];
    let n = Math.max(noise.noise2D(c.clone().scale(config.nscale).array) * 2, 0);
    // n *= n;
    const g = Math.min(1, (c.x-100)/(dimensions.x));
    n *= g;
    let numfound = 0;
    for(var i = 0; i < config.k * n; i++) {
      const a = floatRandomBetween(0, Math.PI*2);
      const l = floatRandomBetween(config.r, config.r*2);
      const pos = new Vec2(Math.cos(a)*l, Math.sin(a)*l).add(c);
      if(vars.grid.getChildAtPosition(pos) === -1) {
        vars.grid.addChildAtPosition(pos, pos);
        vars.activeList.push(pos);
        vars.newPositions.push(pos);
        numfound++;
        break;
      }
    }
    if(numfound === 0) {
      vars.activeList.splice(ri, 1);
    }
    // vars.activeList.length = 0;
    requestAnimationFrame(drawStep);
  } else if(vars.position.y < dimensions.y+config.stagePadding) {
    const walker = new Walker(vars.position.clone());
    while(walker.position.x < dimensions.width) {
    // for(let i = 0; i < config.steps; i++) {
      walker.walk();
      const gp = vars.grid.getGridPos(walker.position);
      let doBreak = false;
      for(let x = -2; x <= 2; x++) {
        for(let y = -2; y <= 2; y++) {
          const _gp = gp.addNew(new Vec2(x, y));
          const body = vars.grid.getChildAtGridPosition(_gp);
          if(body && body !== -1 && body.pos) {
            const diff = walker.position.subtractNew(body.pos);
            const l = diff.length;
            if(l <= body.r*.5) {
              doBreak = true;
              // const dl = body.r*.5 - l;
              // walker.position.add(new Vec2(Math.cos(diff.angle) * dl, Math.sin(diff.angle) * dl))
              break;
            }
          }
          if(doBreak) break;
        }
        if(doBreak) break;
      }
      if(doBreak) break;
    }
    const colour = '#f06';
    drawing.path(walker.bezier).fill('none').stroke({ width: .5, color:colour });
    // drawing.polyline().plot(walker.points).fill('none').stroke({ width: .5, color:colour });
    vars.position.y += dimensions.y / config.numwalkers;
    requestAnimationFrame(drawStep);
  } else {
    console.log('end')
  }
}
const draw = () => {
  drawing.rect(dimensions.width, dimensions.height).fill("none").stroke('#f06');
  // for(var i = 0; i < vars.grid.length; i++) {
  //   const c = vars.grid.getRealPosFromIndex(i);
  //   const r = 10;
  //   drawing.circle(r).stroke('#f06').move(c.x-r*.5, c.y-r*.5);
  // }
  requestAnimationFrame(drawStep);
}


const floatRandomBetween = (min, max) => {
  return Math.random() * (max - min) + min;
};

setup();
const svg = document.body.querySelector('svg');
svg.addEventListener('click', (e) => {
  setup();
});
// svg.addEventListener('pointermove', (e) => {
//   console.clear();
//   const o = svg.getBoundingClientRect();
//   const pos = new Vec2(e.clientX-o.x, e.clientY-o.y);
//   const c = vars.grid.getChildAtPosition(pos);
//   const r = 15;
//   drawing.circle(r).stroke('#f06').move(c.x-r*.5, c.y-r*.5);
//   console.log(vars.grid.getGridPos(pos))
//   // console.log(vars.grid.getChildAtPosition(pos), vars.grid.getArrayPosition(pos), pos);
// });



////////////////////////////////////////////////////////////////
// Simplex Noise utility code. Created by Reinder Nijhoff 2020
// https://turtletoy.net/turtle/6e4e06d42e
// Based on: http://webstaff.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf
////////////////////////////////////////////////////////////////
function SimplexNoise(seed = 1) {
	const grad = [  [1, 1, 0], [-1, 1, 0], [1, -1, 0], [-1, -1, 0],
	            	[1, 0, 1], [-1, 0, 1], [1, 0, -1], [-1, 0, -1],
            		[0, 1, 1], [0, -1, 1], [0, 1, -1], [0, -1, -1] ];
	const perm = new Uint8Array(512);
            		
	const F2 = (Math.sqrt(3) - 1) / 2, F3 = 1/3;
	const G2 = (3 - Math.sqrt(3)) / 6, G3 = 1/6;

	const dot2 = (a, b) => a[0] * b[0] + a[1] * b[1];
	const sub2 = (a, b) => [a[0] - b[0], a[1] - b[1]];
	const dot3 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
	const sub3 = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];

	class SimplexNoise {
		constructor(seed = 1) {
			for (let i = 0; i < 512; i++) {
				perm[i] = i & 255;
			}
			for (let i = 0; i < 255; i++) {
				const r = (seed = this.hash(i+seed)) % (256 - i)  + i;
				const swp = perm[i];
				perm[i + 256] = perm[i] = perm[r];
				perm[r + 256] = perm[r] = swp;
			}
		}
		noise2D(p) {
			const s = dot2(p, [F2, F2]);
			const c = [Math.floor(p[0] + s), Math.floor(p[1] + s)];
			const i = c[0] & 255, j = c[1] & 255;
			const t = dot2(c, [G2, G2]);

			const p0 = sub2(p, sub2(c, [t, t]));
			const o  = p0[0] > p0[1] ? [1, 0] : [0, 1];
			const p1 = sub2(sub2(p0, o), [-G2, -G2]);
			const p2 = sub2(p0, [1-2*G2, 1-2*G2]);
			
			let n =  Math.max(0, 0.5-dot2(p0, p0))**4 * dot2(grad[perm[i+perm[j]] % 12], p0);
			    n += Math.max(0, 0.5-dot2(p1, p1))**4 * dot2(grad[perm[i+o[0]+perm[j+o[1]]] % 12], p1);
		    	n += Math.max(0, 0.5-dot2(p2, p2))**4 * dot2(grad[perm[i+1+perm[j+1]] % 12], p2);
			
			return 70 * n;
		}
		hash(i) {
            i = 1103515245 * ((i >> 1) ^ i);
            const h32 = 1103515245 * (i ^ (i>>3));
            return h32 ^ (h32 >> 16);
		}
	}
	return new SimplexNoise(seed);
}
              
            
!
999px

Console