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 is required to process package imports. If you need a different preprocessor remove all packages first.

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

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

              
                <canvas id=canvas width="1500" height="640"></canvas>
              
            
!

CSS

              
                body{background:black}
canvas{width:100%;height:100%}
              
            
!

JS

              
                const len=({x,y})=>Math.sqrt(x**2+y**2)
const subtract=(a,b)=>
  ({x:a.x-b.x,y:a.y-b.y});
const add=(a,b)=>
  ({x:a.x+b.x,y:a.y+b.y});
const distance=(from,to)=>
  len(subtract(to,from));
const azimuth=(p)=>
  Math.atan2(p.y,p.x);

const direction=(from,to)=>
  azimuth(subtract(to,from))

const polar=(a,r)=>
  ({x:Math.cos(a)*r,y:Math.sin(a)*r});
const scalar=(a,b)=>a.x*b.x+a.y*b.y
const point2array=(p)=>[p.x,p.y]
const scale=(p,s)=>({x:p.x*s,y:p.y*s})
const normalize=(p)=>scale(p,1.0/len(p))
const normal=({x,y})=>({x:-y,y:x})
const offsetAlong=(p,edge)=>{
  const p_rel=subtract(p,edge.from);
  const to_rel=subtract(edge.to,edge.from);
  return scalar(p_rel,to_rel)/len(to_rel);
}
const atOffsetAlong=(o,edge)=>
  add(edge.from,scale(normalize(subtract(edge.to,edge.from)) ,o));
function nearestOnEdge(p,edge){
  const o = offsetAlong(p,edge)
  if(o<0)
    return edge.from;
  if(distance(edge.from,edge.to)<o)
    return edge.to;
  return atOffsetAlong(o,edge);
}
const ctx = canvas.getContext('2d');
ctx.lineWidth = 1;

function circle(c,pen){
  ctx.fillStyle=pen
  ctx.beginPath();
  ctx.arc(c.x, c.y, c.r, 0, 2 * Math.PI);
  ctx.fill();
}

function branch(from,to){
  circle(from,from.color||'red')
  circle(to,to.color||'red')
  const gradient = 
    ctx.createLinearGradient(from.x,from.y, to.x,to.y);

  gradient.addColorStop(0, from.color||'red');
  gradient.addColorStop(1, to.color||'red');
  ctx.fillStyle=gradient
  const d=distance(from,to);
  const cos=(from.r-to.r)/d;
  const a=Math.acos(cos);
  const b=direction(from,to);
  const points=[];
  for(let i=-1;i<=1;i+=2){
    const c = b+i*a;
    [from,to].map(p=>
      points.push(add(p,polar(c,p.r)))
    )  
  }
  const arrays=points.map(point2array)
  ctx.beginPath();
  ctx.moveTo(...arrays[0]);
  ctx.lineTo(...arrays[1]);
  ctx.lineTo(...arrays[3]);
  ctx.lineTo(...arrays[2]);
  ctx.closePath();
  // ctx.strokeStyle='white';
  ctx.fill();
}
function putPixel({x,y},color){
  ctx.fillStyle = color;
  ctx.fillRect( x, y, 1, 1 );
}
function drawVirus(e){
  const LEGS=6;
  const t=e.phase+Date.now()/200;
  for(let i=0;i<LEGS;++i){
    const dir=polar(i/LEGS*Math.PI*2,1);
    const other=normal(dir);
    const LEN=7;
    for(let j=0;j<LEN;++j){
      const pixelPos=add(e,add(
        scale(dir,e.r+j),
        scale(other,Math.sin(t+j/LEN*Math.PI)*3)
      ))
      putPixel(pixelPos,'black');
    }
  }
  circle(e,'black');
}
function drawCrystal(e){
  const t=e.phase+Date.now()/200;
  const points=[0,1,2].map(i=>point2array(add(e,polar(t+i/3*2*Math.PI,e.r))))
  ctx.beginPath();
  ctx.moveTo(...points[0]);
  for(let i=1;i<points.length;++i){
    ctx.lineTo(...points[i]);
  }
  ctx.closePath();
  ctx.fillStyle='green';
  ctx.fill();  
}
function drawHero(e){
  const o={...e,r:Math.min(e.r,12)};
  if(e.infectedUntil>Date.now()){
    const gradient=ctx.createRadialGradient(e.x,e.y,0, e.x,e.y,o.r);
    gradient.addColorStop(0,'red');
    gradient.addColorStop(1,'white');   
    return circle(o,gradient);
  }
  if(!e.big){
    return circle(o,'white');
  }
  const gradient=ctx.createRadialGradient(e.x+4,e.y-4,4, e.x,e.y,10);
  const c = Date.now()%500<200;
  gradient.addColorStop(0,c?'pink':'lightblue');
  gradient.addColorStop(0.9,'white');
  gradient.addColorStop(1,c?'lightblue':'yellow');
  circle(o,gradient);
}
function drawEntity(e){
  ({
    'virus':drawVirus,
    'hero':drawHero,
    'blood':(e)=>circle(e,'blue'),
    'food':(e)=>circle(e,'rgb(100,0,0)'),
    'crystal':drawCrystal,
  })[e.role](e);
}

function draw(){
  ctx.fillStyle='black';
  ctx.fillRect(0,0,canvas.width,canvas.height);
  edges.forEach(e=>
    branch({
      ...e.from,
      color:'violet',
      r:e.from.r+3,
    },{
      ...e.to,  
      color:'violet',
      r:e.to.r+3,
    })
  )
  edges.forEach(e=>branch(e.from,e.to));
  hero.options.forEach(e=>{if(e)circle({
    ...e,
    r:e.r+2
  },'white')});
  entities.forEach(e=>{
    if(hero.swap&&(hero==e||hero.swap.other==e)){
      const f=(Date.now()-hero.swap.start)/SWAP_DURATION_MS;
      const f2=hero==e?f:1-f;
      const route=subtract(hero.swap.other,hero);
      const side=normal(normalize(route));
      const pos=add(
        add(hero,scale(route,f2)),
        scale(side,Math.sin(f*Math.PI)*10*(hero==e?1:-1))
      );
      drawEntity({
        ...e,
        ...pos,
      });
    }else{
      drawEntity(e);
    }
  });
  if(selectedNode)circle(selectedNode,'yellow');
  window.requestAnimationFrame(draw)
}
// Set line width
let nodes=[{"x":30,"y":90,"r":15},
{"x":100,"y":40,"r":15},
{"x":350,"y":50,"r":15},
{"x":500,"y":100,"r":15},
{"x":834,"y":150,"r":15,"color":"darkblue"},
{"x":100,"y":210,"r":15},
{"x":410,"y":420,"r":15,"color":"purple"},
{"x":200,"y":400,"r":15},
{"x":645,"y":83,"r":15},
{"x":793,"y":489,"r":15},
{"x":317,"y":130,"r":15},
{"x":472,"y":231,"r":15},
{"x":785,"y":476,"r":15},
{"x":765,"y":450,"r":15},
{"x":401,"y":137,"r":15},
{"x":50,"y":438,"r":15},
{"x":229,"y":571,"r":15},
{"x":628,"y":600,"r":15},
{"x":249,"y":567,"r":15,"color":"darkblue"},
{"x":548,"y":29,"r":15},
{"x":899,"y":32,"r":15},
{"x":1263,"y":133,"r":15},
{"x":1005,"y":130,"r":15},
{"x":892,"y":107,"r":15,"color":"darkblue"},
{"x":894,"y":222,"r":15},
{"x":1101,"y":235,"r":15},
{"x":1239,"y":248,"r":15},
{"x":907,"y":348,"r":15},
{"x":1241,"y":372,"r":15,"color":"darkblue"},
{"x":879,"y":426,"r":15},
{"x":1211,"y":494,"r":15},
{"x":870,"y":502,"r":15},
{"x":1194,"y":584,"r":15,"color":"purple"},
{"x":931,"y":599,"r":15}]
let edges=[{"from":0,"to":1},
{"from":1,"to":2},
{"from":2,"to":3},
{"from":3,"to":4},
{"from":5,"to":0},
{"from":4,"to":6},
{"from":6,"to":5},
{"from":6,"to":7},
{"from":7,"to":5},
{"from":4,"to":9},
{"from":9,"to":6},
{"from":1,"to":10},
{"from":10,"to":11},
{"from":11,"to":5},
{"from":11,"to":4},
{"from":6,"to":11},
{"from":5,"to":15},
{"from":15,"to":16},
{"from":16,"to":17},
{"from":17,"to":9},
{"from":6,"to":16},
{"from":2,"to":19},
{"from":19,"to":20},
{"from":20,"to":21},
{"from":21,"to":22},
{"from":22,"to":23},
{"from":23,"to":24},
{"from":24,"to":25},
{"from":25,"to":26},
{"from":26,"to":27},
{"from":27,"to":28},
{"from":28,"to":29},
{"from":29,"to":30},
{"from":30,"to":31},
{"from":31,"to":32},
{"from":32,"to":33},
{"from":33,"to":17}]



nodes.forEach(n=>{
  n.goal_x=n.x;
  n.goal_y=n.y;
  n.goal_r=n.r;
  n.rate=Math.PI*2/1000;
  n.phase=Math.random()*Math.PI*2;
  n.amplitude=Math.random()*10;
})
edges.forEach((e)=>{
  e.from=nodes[e.from];
  e.to=nodes[e.to];
});
edges.forEach(e=>{
  e.next=edges.filter(edge=>edge.from==e.to);
  e.previous=edges.filter(edge=>edge.to==e.from);
});
let entities=edges.map(e=>
  [0,1,2,3,4,5].map(z=>({
    r:5+Math.random()*3,
    edge:e,
    phase:Math.random()*2*Math.PI,
    role:['blood','food','virus','crystal'][z%4],
    ...atOffsetAlong(distance(e.from,e.to)*z/6,e)
  }))                        
).flat();
const hero={
  r:1,
  color:'white',
  x:0,
  y:0,
  phase:0,
  edge:edges[0],
  role:'hero',
  options:[],
}
entities.push(hero);
selectedNode=null;

function updateEntity(e){
  if(!e.edge){
    e.edge=edges[edges
      .map((edge,i)=>({i,d:distance(e,nearestOnEdge(e,edge))}))
      .sort(({d:a},{d:b})=>a-b)[0].i]
  }
  const edge=e.edge;
  let o = offsetAlong(e,edge);
  const speed=e.speed||1;
  o+=speed;
  if(o<0){
    o=0;
  }else if(distance(edge.to,edge.from)<o){
    e.edge.sortedEntities=e.edge.sortedEntities.filter(en=>en!=e)
    e.edge=edge.next[Math.random()*edge.next.length|0]
    e.edge.sortedEntities.unshift(e)
  }
  const otherAxis=normal(normalize(subtract(edge.to,edge.from)));
  const new_pos=add(
    scale(otherAxis,4*Math.sin(e.phase+Date.now()/500)),
    atOffsetAlong(o,edge)
  );
  
  e.x=new_pos.x;
  e.y=new_pos.y;
}
function updateNode(node){
  node.x=node.goal_x+node.amplitude*Math.sin(node.phase+node.rate*Date.now());
  node.y=node.goal_y+node.amplitude*Math.cos(node.phase+node.rate*Date.now()); 
  node.r=node.goal_r+node.amplitude*(Math.cos(node.phase+node.rate*Date.now())**2); 
}
function updateEdge(edge){
  const crowd=entities.filter(n=>n.edge==edge)
  const os=crowd.map((n)=>
    ({o:offsetAlong(n,edge),n})
  ).sort(({o:o1},{o:o2})=>o1-o2)
  edge.sortedEntities=os.map(({n})=>n);
  os.forEach(({o,n},p)=>{
    n.speed=2;
    if(0<p && p+1<os.length){
      const b = o-os[p-1].o;
      const a = os[p+1].o-o;
      n.speed=(a/(b+a))*4;
    }
    
  })
}
function collect(edge,idx){
  const ses=edge.sortedEntities;
  if(idx<0){
    return edge.previous.map(e=>collect(e,e.sortedEntities.length+idx)).flat()
  }else if(ses.length<=idx){
    return edge.next.map(e=>collect(e,idx-ses.length)).flat()
  }
  return [ses[idx]];
}
function updateOptions(){
  if(hero.swap){
    hero.options=[];
  }else{
    const ses=hero.edge.sortedEntities;
    const idx=ses.indexOf(hero);
    hero.options=[collect(hero.edge,idx+2),collect(hero.edge,idx-2)].flat();
  }
}
const SWAP_DURATION_MS=200;
function step(){
  if(hero.swap && hero.swap.start+SWAP_DURATION_MS<Date.now()){
    const oldPos={x:hero.x,y:hero.y,edge:hero.edge};
    hero.x=hero.swap.other.x;
    hero.y=hero.swap.other.y;
    hero.edge=hero.swap.other.edge;
    
    hero.swap.other.x=oldPos.x;
    hero.swap.other.y=oldPos.y;
    hero.swap.other.edge=oldPos.edge;
    if(hero.swap.other.role=='food'){
      hero.r++;
      if(hero.r>=12){
        hero.big=true;
      }
    }
    if(hero.swap.other.role=='food'||hero.big&&hero.swap.other.role=='virus'){
      entities=entities.filter(e => e != hero.swap.other);
    }
    hero.swap=null;
  }
  edges.forEach(updateEdge)
  entities.forEach(updateEntity)
  nodes.forEach(updateNode)
  updateOptions()
  setTimeout(step,50);
}
draw()
step()

document.addEventListener('keydown',(e)=>{
  if(hero.swap||selectedNode||hero.infectedUntil>Date.now())return;
  const dir={
    ArrowRight:{x:1,y:0},
    ArrowLeft:{x:-1,y:0},
    ArrowUp:{x:0,y:-1},
    ArrowDown:{x:0,y:1},
  }[e.key];
  if(dir){
    const best=hero.options.map((e)=>
      ({e,s:scalar(dir,normalize(subtract(e,hero)))})
    ).filter(({s})=>s>0).sort(({s:s1},{s:s2})=>s2-s1)[0];
    if(best){
      hero.swap={other:best.e,start:Date.now()};
      if(!hero.big && best.e.role=='virus'){
        hero.infectedUntil=Date.now()+4000;
      }
    }
  }
});
window.focus();
canvas.click();
              
            
!
999px

Console