Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ 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

Auto Save

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

              
                <div id="stage">
  <canvas id="canvas"></canvas>
  <a id="imageLink" href="" download>
    <img id="image"/>
  </a>
</div>
              
            
!

CSS

              
                body
  background: #333332

#stage 
  position: absolute
  width: 800px
  height: 800px
  margin: auto
  top: 0
  bottom: 0
  left: 0
  right: 0
  background: #ffffff
  
.particle
  display: none
  position: absolute
  top: 0
  left: 0
  
.particleDisplay
  position: absolute
  width: 100px
  height: 100px
  transform: translate3d(-50px, -50px, 0)
  background: rgba(0,0,0,0.2)
  
.activator
  display: none
  position: absolute
  top: 0
  left: 0
  
.activatorDisplay
  position: absolute
  width: 10px
  height: 10px
  transform: translate(-5px, -5px)
  background: rgba(255,0,0,1)
 
#canvas
  position: absolute
  top: 0
  left: 0

#image
  display: none
  position: absolute
  top: 0
  left: 0
              
            
!

JS

              
                import $ from "https://cdn.skypack.dev/jquery@3.6.0";
var settings = {
  numParticles: 512,
  numActivators: 9,
  cellSizeX: 100,
  cellSizeY: 100,
  numFrames: 400,
  record: false
};


let frameCount = 0;
let particles = Array.apply(null, { length: settings.numParticles });
let activators = Array.apply(null, { length: settings.numActivators });
const $stage = $("#stage");
const $canvas = $("#canvas");
const $image = $("#image");
var stageWidth = $stage.width();
var stageHeight = $stage.height();
var cellParticles = [];
var numCellsX = Math.ceil(stageWidth / settings.cellSizeX);
var numCellsY = Math.ceil(stageHeight / settings.cellSizeY);
var rAF;


const encoder = new GIFEncoder(stageWidth, stageHeight);
encoder.setRepeat(0);
encoder.setDelay(1000/60);

//----------------------------------------------------------------

class Activator {
  constructor(index) {
    this.age = 0;
    this.adjacentParticles = [];
    this.index = index;
  }
}

class Particle {
  constructor(index) {
    this.x = 0;
    this.y = 0;
    this.power = 0;
    this.$el = null;
    this.index = index;
  }
}

//----------------------------------------------------------------

setup();

//----------------------------------------------------------------

function setup() {
  particles = particles.map((p, i) => {
    p = new Particle(i);
    p.x = (stageWidth + settings.cellSizeX * 2) * Math.random();
    p.y = stageHeight * Math.random();
    p.cell = getCellLocation(p.x, p.y);
    p.$el = $(`
      <div class='particle'>
        <div class='particleDisplay'></div>
      </div>
    `);
    p.$el.css("transform", `translate3d(${p.x}px, ${p.y}px, 0px)`);
    // $stage.append(p.$el);
    return p;
  });

  activators = activators.map((a, i) => {
    a = new Activator(i);
    a.x = settings.cellSizeX * 2 * (1+ (i % ((numCellsX/2) - 1)));
    a.y = settings.cellSizeY * 2 * (1 + Math.floor(i / (Math.floor(numCellsX/2) - 1)));
    a.homeX = a.x;
    a.homeY = a.y;
    a.cell = getCellLocation(a.x, a.y);
    a.angle = i * Math.PI / 2;
    a.$el = $(`
      <div class='activator'>
        <div class='activatorDisplay'></div>
      </div>
    `);
    a.$el.css("transform", `translate3d(${a.x}px, ${a.y}px, 0px)`);
    // $stage.append(a.$el);
    return a;
  });
  $canvas[0].width = stageWidth;
  $canvas[0].height = stageHeight;
  encoder.start();
  loop();
}

function loop() {
  updateActivators();
  updateParticles();
  draw();
  rAF = requestAnimationFrame(loop);
  frameCount++;
}

function updateActivators() {
  //chill for now
  activators.forEach((a) => {
    a.angle += 2 * 2 * Math.PI / settings.numFrames;
    a.x = a.homeX + Math.cos(a.angle) * 20;
    a.y = a.homeY + Math.sin(a.angle) * 20;
    a.cell = getCellLocation(a.x, a.y);
  });
}

function updateParticles() {
  cellParticles = [];
  var fullTripX = stageWidth + settings.cellSizeX * 2;
  particles.forEach((p, i) => {
    p.power = 0;
    
    p.x += fullTripX / settings.numFrames;
    p.y += 0;
    
    if (p.x > stageWidth + settings.cellSizeX){
      p.x -= stageWidth + settings.cellSizeX * 2;
    }
    
    p.cell = getCellLocation(p.x, p.y);
    addToCell(p.cell.x, p.cell.y, p);
  });
  
  
  // console.log("updateParticles:: activators")
  activators.forEach((a, i) => {
    a.adjacentParticles = getParticlesInAdjacentCells(a.cell.x, a.cell.y);
    // get distance to each particle
    a.distances = a.adjacentParticles.map((p, j) => {
      return dist(a.x, a.y, p.x, p.y);
    });
    a.adjacentParticles.forEach((p, i) => {
      //  activator strengh is proportional to distance to particle (and velocity?)
      //    actuator vectors on a single particle are additive (could change the blend equation later)
      //    particle can trigger an event or be simple power comparison with easing
      p.power += 100  / a.distances[i];
    });
  });
}

function getParticlesInAdjacentCells(x, y) {
  let adjacentParticles = [];
  for (let i = x - 1; i <= x + 1; i++) {
    if (i >= 0 && i < numCellsX) {
      for (let j = y - 1; j <= y + 1; j++) {
        if (j >= 0 && j < numCellsY) {
          adjacentParticles = adjacentParticles.concat(getCell(i,j));
        }
      }
    }
  }
  return adjacentParticles;
}

function updateParticlePower() {}

function getCell(x, y) {
  if (!cellParticles[x]) cellParticles[x] = [];
  if (!cellParticles[x][y]) cellParticles[x][y] = [];
  return cellParticles[x][y];
}

function addToCell(x, y, particle) {
  if (!cellParticles[x]) cellParticles[x] = [];
  if (!cellParticles[x][y]) cellParticles[x][y] = [];
  cellParticles[x][y].push(particle);
  return cellParticles[x][y];
}

function getCellLocation(x, y) {
  // console.log("getCellLocation");
  return {
    x: Math.floor(numCellsX * (x / stageWidth)),
    y: Math.floor(numCellsY * (y / stageHeight))
  };
}

function dist(x1, y1, x2, y2) {
  return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}

function draw() {
  // draw to stage
  var ctx = $canvas[0].getContext("2d");
  ctx.fillStyle  = "#ffffff";
  ctx.fillRect(0, 0, $canvas[0].width, $canvas[0].height);
  particles.forEach((p, i) => {
    p.$el.css({
      transform: 
      `translate3d(${p.x}px, ${p.y}px, 0px) scale(${Math.min(1, p.power)})`
    });
  });

  activators.forEach((a, i) => {
    a.adjacentParticles.forEach((p, i) => {
      ctx.beginPath();
      ctx.moveTo(p.x, p.y);
      ctx.lineTo(a.x, a.y);
      ctx.strokeStyle = `rgba(0,0,0,${Math.pow(Math.max(0, 1 - (a.distances[i] / (2 * settings.cellSizeX))), 5)})`;
      ctx.stroke();
    });
  });
  if (settings.record){
    if (frameCount < settings.numFrames){
      encoder.addFrame(ctx);
    } else if (frameCount == settings.numFrames){
      stopRecording();
      cancelAnimationFrame(rAF)
    }
  }
}

function stopRecording() {
  if (encoder.hasFinished) return;
  encoder.finish();    //a
  encoder.hasFinished = true;
  const stream = encoder.stream();
  const data = stream.getData();
  $image.show();
  $image[0].src = 'data:image/gif;base64,' + encode64(data);
  $("#imageLink").attr("href", $image[0].src)
  encoder.download("download.gif");
}
              
            
!
999px

Console