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 id="frameCounter"></div>
</div>
              
            
!

CSS

              
                body
  background: #333332

#stage 
  position: absolute
  width: 95vh
  height: 95vh
  margin: auto
  top: 0
  bottom: 0
  left: 0
  right: 0
  background: #222222
  filter: drop-shadow(0 0 20px rgba(0,0,0,0.5))
  
.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
  height: 95vh
  width: 95vh

#image
  display: none
  position: absolute
  top: 0
  left: 0
#frameCounter
  color: white
  background: black
  font-family: "Courier New"
  font-size: 15px
  position: absolute
  padding: 3px
  z-index: 10000
              
            
!

JS

              
                import $ from "https://cdn.skypack.dev/jquery@3.6.0";

let TAU = Math.PI * 2;
let HALF_TURN = Math.PI;
let QUARTER_TURN = TAU / 4;

var stageWidth = 1080;
var stageHeight = 1080;

let numRows = 8;
let numCols = 3;

var settings = {
  numParticles: 2800,
  numActivators: 12
  ,//numRows * numCols,
  cellSizeX: stageWidth / 8,
  cellSizeY: stageHeight / 8,
  numFrames: 480 * 2,
  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 cellParticles = [];
var numCellsX = Math.ceil(stageWidth / settings.cellSizeX);
var numCellsY = Math.ceil(stageHeight / settings.cellSizeY);
var rAF;


let borderX = settings.cellSizeX * 2;
let borderY = settings.cellSizeY * 2;

let fullTripX = stageWidth + borderX * 2;
let fullTripY = stageHeight + borderY * 2;

const zip = new JSZip();

let colormapOffsetX = 0;

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

// $(window).click(() => {
//   if(settings.record == false){
//     settings.record = true;
//     frameCount = 0;
//   }
// })

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

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;
  }
}

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

loadColorMap(setup);

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

function setup() {
  particles = particles.map((p, i) => {
    p = new Particle(i);
    p.x = fullTripX * Math.random() - settings.cellSizeX;
    p.y = fullTripY * Math.random() - settings.cellSizeY;
    
    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.col = i % numCols;
    a.row = Math.floor(i/numCols);
    
//     a.x = (stageWidth + borderX * 2) * ((-1 + a.col) / (numCols));
//     a.y = (stageHeight  + borderX*2 ) * ((-1 + a.row) / numRows);
    
    
    
    a.homeX = a.x = stageWidth / 2;
    a.homeY = a.y = stageWidth / 2;
    a.cell = getCellLocation(a.x, a.y);
    a.angle = -i * TAU / (settings.numActivators);
    
    // if (i == settings.numActivators / 2){
    //   a.angle = -(settings.numActivators) * TAU / (settings.numActivators + 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);
    
    
    // console.log(`activator ${i}`,a.row, a.col, " | x,y:", a.x, a.y)
    return a;
  });
  $canvas[0].width = stageWidth;
  $canvas[0].height = stageHeight;
  //$stage.css({
  //  "width": stageWidth + "px",
  //  "height": stageHeight + "px",
  //})
  
  // initial Fill
  var ctx = $canvas[0].getContext("2d");
  ctx.globalCompositeOperation = "source-over";
  ctx.fillStyle = `rgba(${0x22},${0x22},${0x22},1)`;
  ctx.fillRect(0, 0, stageWidth, stageHeight);
  
  loop();
  updateActivators();
}

function loop() {
  // console.log("----------- loop() ------------")
  updateActivators();
  updateParticles();
  draw();
  rAF = requestAnimationFrame(loop);
  frameCount++;
}

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

function updateActivators() {
  //chill for now
  activators.forEach((a, i) => {
    let dir = 1//(i * 1.25) % 2 ? -1 : 1;
    a.angle += dir * TAU / settings.numFrames;
    let wobble = 350;
    let radius = 200;
    let speed = fullTripX / settings.numFrames
    let angle = 0;
    
    // a.homeX += speed;
    // a.homeY -= speed;
    
    if (a.homeX > stageWidth + borderX ){
      a.homeX -= fullTripX;
    }
    if (a.homeX < -borderX){
      a.homeX += fullTripX;
    }
    if (a.homeY > stageHeight + borderY){
      a.homeY -= fullTripY;
    }
    if (a.homeY < -borderY){
      a.homeY += fullTripY;
    }
    
    a.x = a.homeX + Math.cos(a.angle) * wobble;
    a.y = a.homeY + Math.sin(a.angle) * wobble;
    
    a.cell = getCellLocation(a.x, a.y);
  });
}

function updateParticles() {
  // colormapOffsetX = (colormapOffsetX + 1) % 100;
  cellParticles = [];
  let angle = Math.PI / 2;
  let speed = fullTripX / settings.numFrames
  particles.forEach((p, i) => {
    p.power = 0;
    let modifiedAngle = 0;
    p.x += speed * Math.cos(angle + modifiedAngle);
    p.y += speed * Math.sin(angle + modifiedAngle);
    
    if (p.x > stageWidth + borderX){
      p.x -= fullTripX;
    }
    if (p.x < -borderX){
      p.x += fullTripX;
    }
    if (p.y > stageHeight + borderY){
      p.y -= fullTripY;
    }
    if (p.y < -borderY){
      p.y += fullTripY;
    }
    
    p.color = getPixel(colorMapData, (p.x + colormapOffsetX) / stageWidth, p.y / stageHeight);
    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
      let maxDistance = settings.cellSizeX * 1.7;
      let newPower =  Math.max(0, 1 - a.distances[i] / maxDistance)
      p.power += newPower;
    });
    
    // console.log(`activator ${i}`,a.row, a.col, " | x,y:", a.x, a.y)
    
    
  });
}

function getParticlesInAdjacentCells(x, y) {
  let adjacentParticles = [];
  for (let i = x - 2; i <= x + 2; i++) {
    if (i >= 0 && i < numCellsX) {
      for (let j = y - 2; j <= y + 2; 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 draw() {
  let HALF_PI = Math.PI / 2;
  // draw to stage
  var ctx = $canvas[0].getContext("2d");
  ctx.globalCompositeOperation = "source-over";
  ctx.fillStyle = `rgba(${0x22},${0x22},${0x22},0.5)`;
  ctx.fillRect(0, 0, $canvas[0].width, $canvas[0].height);
  // ctx.clearRect(0, 0, $canvas[0].width, $canvas[0].height);
  ctx.globalCompositeOperation = "screen";
  // ctx.globalCompositeOperation = "multiply";
  // ctx.fillStyle  = "rgba(0,0,0,0.1)";
  particles.forEach((p, i) => {
    // p.$el.css({
    //   transform: 
    //   `translate3d(${p.x}px, ${p.y}px, 0px) scale(${Math.min(1, p.power)})`
    // });
    
    let a = p.power * p.power * p.power *0.25;
    
    // ctx.fillStyle  = `rgba(${r},${g},${b},${a})`;
    ctx.fillStyle  = `rgba(${p.color >> 16},${(p.color >> 8) & 0xff},${p.color & 0xff},${a})`;
    
    // console.log(`rgba(${p.color >> 16},${(p.color >> 8) & 0xff},${p.color & 0xff},${a})`)
    let rad = 75
    let w = p.power * rad
    let h = p.power * rad
    
    let SIXTY_RAD = (2 * Math.PI) / 6;
    
    ctx.beginPath();
    
//     ctx.moveTo(
//       p.x + p.power * rad * Math.cos(HALF_PI),
//       p.y + p.power * rad * Math.sin(HALF_PI)
//     );
    
//     ctx.lineTo(
//       p.x + p.power * rad * Math.cos(2 * SIXTY_RAD + HALF_PI),
//       p.y + p.power * rad * Math.sin(2 * SIXTY_RAD + HALF_PI)
//     );
    
//     ctx.lineTo(
//       p.x + p.power * rad * Math.cos(4 * SIXTY_RAD + HALF_PI),
//       p.y + p.power * rad * Math.sin(4 * SIXTY_RAD + HALF_PI)
//     );
    
    
    
    // ctx.fillRect(p.x-w/2, p.y-h/2,w, h);
    // ctx.arc(p.x, p.y, p.power * rad, 0, TAU);
    // ctx.fill();
    
    let center = {x: stageWidth * 0.5, y: stageHeight * 0.5};
    // let angleToCenter = Math.atan2(p.y - center.y, p.x - center.x);
    
    
    let angleToCenter = -Math.atan2(center.y - p.y, center.x - p.x);
    
    
    drawRotatedSquare(ctx, p.x, p.y, w, angleToCenter)
    
  });

  activators.forEach((a, i) => {
    // ctx.fillStyle = "#F0F"
    // ctx.fillRect(a.x, a.y, 10, 10);
    // ctx.fill();
//     a.adjacentParticles.forEach((p, i) => {
//       ctx.beginPath();
//       ctx.moveTo(p.x, p.y);
//       ctx.lineTo(a.x, a.y);
      
//       let maxDistance = settings.cellSizeX * 1;
//       let newPower =  Math.max(0, 1 - a.distances[i] / maxDistance)
//       ctx.strokeStyle = `rgba(0,0,0,${newPower})`;
//       ctx.stroke();
//     });
  });
  if (settings.record){
    if (frameCount < settings.numFrames){
      $("#frameCounter").text( pad(frameCount, 3));
      zip.file(
        `frame_${pad(frameCount, 3)}.png`, 
        dataURItoBlob($canvas[0].toDataURL( 'image/png' )), 
        {base64: true}
      );
    } else if (frameCount == settings.numFrames){
      stopRecording();
      cancelAnimationFrame(rAF)
    }
  }
}


function stopRecording() {
  zip.generateAsync({type:"blob"})
    .then(function(content) {
        // see FileSaver.js
        saveAs(content, "frames.zip");
    });
  
  
}

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

function pad(num, len){
  while(num.toString().length < len ){
    num = "0" + num.toString()
  }
  return num;
}

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

function dataURItoBlob( dataURI ) {
    // Convert Base64 to raw binary data held in a string.

    var byteString = atob(dataURI.split(',')[1]);

    // Separate the MIME component.
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

    // Write the bytes of the string to an ArrayBuffer.
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // Write the ArrayBuffer to a BLOB and you're done.
    var bb = new Blob([ab]);

    return bb;
}

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

function drawRotatedSquare(ctx, x, y, size, angle){
  let halfSize = size * 0.5;
  let x0 = -halfSize;
  let x1 = halfSize;
  let y0 = -halfSize;
  let y1 = halfSize;

  let points = [];
  points.push([x0, y0]);
  points.push([x1, y0]);
  points.push([x1, y1]);
  points.push([x0, y1]);
  
points = points.map(p => getRotatedPoint(p[0], p[1], angle));
points = points.map(p => [x + p[0], y + p[1]]);
  
  ctx.beginPath();
  ctx.moveTo(points[0][0],points[0][1]);
  ctx.lineTo(points[1][0],points[1][1]);
  ctx.lineTo(points[2][0],points[2][1]);
  ctx.lineTo(points[3][0],points[3][1]);
  ctx.lineTo(points[0][0],points[0][1]);
  ctx.closePath();
  ctx.fill();
}

function getRotatedPoint(x,y, angle){
  let cos = Math.cos(angle),
      sin = Math.sin(angle),
      nx = (cos * x) + (sin * y),
      ny = (cos * y) - (sin * x);
    return [nx, ny];
}

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

var colorMap;
var colorMapCanvas;
var colorMapCtx;
var colorMapData;

function loadColorMap(callback) {
	var imgSrc = 
 "https://assets.codepen.io/98232/Imagemap+2048_1.png";
  //"https://assets.codepen.io/98232/comp54.jpg";
	colorMap = new Image();
	colorMap.crossOrigin = "anonymous";
	colorMap.src = imgSrc;
	colorMap.onload = function() {
		postColorMapLoad();
		callback();
	};
}

function postColorMapLoad() {
	// create the sampler
	var colorMapCanvas = document.createElement("canvas");
  // $("body").append($(colorMapCanvas));
	colorMapCanvas.height = colorMapCanvas.width = 2048;
	colorMapCtx = colorMapCanvas.getContext("2d");
	colorMapCtx.drawImage(colorMap, 0, 0, 2048, 2048);
	colorMapData = colorMapCtx.getImageData(0, 0, 2048, 2048);
}

function getPixel(colorMapData, propX, propY) {
	var data = colorMapData.data;
	var col = (propX * colorMapData.width) << 2;
	var row = (propY * colorMapData.height) >> 0;
	var rowWidth = colorMapData.width << 2;
	return (data[col + (row * rowWidth) + 0] << 16) | (data[col + (row * rowWidth) + 1] << 8) | data[col + (row * rowWidth) + 2];
}
              
            
!
999px

Console