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

              
                <canvas id="canvas" width="500" height="500">drawing…hopefully…</canvas>
              
            
!

CSS

              
                html,
body {
  overflow: hidden;
  padding: 0;
  margin: 0;
  width: 100vw;
  height: 100vh;
  width: 100dvw;
  height: 100dvh;
  width: 100mvw;
  height: 100mvh;
}

canvas {
  width: 100vw;
  height: 99vh;
}

              
            
!

JS

              
                // Set up a grid
// Draw shapes at each gridpoint
// - orient in a pattern
// - give each a reflective direction (think 'normal map' in 3D)
// - change color depending on difference in angle from pointer to shape's reflective direction.

// Universal constants
const TAU = Math.PI * 2;

// Artwork variables
const hueRange = 10;
const hueShift = 210;

// Prepare canvas
const canvas = document.getElementById("canvas");
const pxWidth = window.innerWidth * window.devicePixelRatio;
const pxHeight = window.innerHeight * window.devicePixelRatio;
canvas.width = pxWidth;
canvas.height = pxHeight;
const ctx = canvas.getContext("2d");
ctx.globalCompositeOperation = "source-over";

const smallestSide =
  canvas.width > canvas.height ? canvas.height : canvas.width;
const gridSize = Math.round(smallestSide * 0.16);

// Initialise pointer position to the center of the canvas
let mouseX = -pxWidth;
let mouseY = -pxHeight;

function getIsometricCoords([px, py]) {
  const origin = [canvas.width * 0.5, canvas.height * 0.5];
  const [ox, oy] = origin;
  const gridSeparation = gridSize; //Math.round(canvas.height * 0.01)
  const dy = Math.sin((TAU * 60) / 360) * gridSeparation;
  let x;
  let y;

  x = gridSeparation * px;
  if (!!(py % 2)) {
    x = x + gridSeparation * 0.5;
  }
  y = dy * py;

  const useAlternativeOrientation = true;
  if (useAlternativeOrientation) {
    // Rotate angles by 30°
    const rotate = TAU / 12;
    [x, y] = [
      x * Math.cos(rotate) - y * Math.sin(rotate),
      x * Math.sin(rotate) + y * Math.cos(rotate)
    ];
  }

  // Translate to our chosen grid origin
  x = x + ox;
  y = y + oy;

  return [x, y];
}

const gridCoordinates = [
  [-1, -2],
  [0, -2],
  [1, -2],
  [-2, -1],
  [-1, -1],
  [0, -1],
  [1, -1],
  [-2, 0],
  [-1, 0],
  [1, 0],
  [2, 0],
  [-2, 1],
  [-1, 1],
  [0, 1],
  [1, 1],
  [-1, 2],
  [0, 2],
  [1, 2]
]
  .map(getIsometricCoords)
  .map(([x, y]) => {
    return { x, y };
  });

// Fill canvas
function clearCanvas() {
  ctx.globalCompositeOperation = "source-over";
  ctx.fillStyle = "#000";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}

// Prepare shape data
const hexagonsData = gridCoordinates.map((position, index) => {
  const size = gridSize * 0.575;
  const shape = {
    x: position.x,
    y: position.y,
    size,
    spin: 0,
    tHueShift: 0,
    normal: TAU * 0.6,
    rotation: 0, //TAU / 6,
    random: Math.random() - 0.5,
    disalignmentRate: Math.random() - 0.5
  };
  shape.normal =
    TAU * 0.5 +
    Math.atan2(
      position.y - canvas.height * 0.5,
      position.x - canvas.width * 0.5
    );
  shape.targetNormal = shape.normal;
  return shape;
});

function cross(a, b) {
  return a.x * b.y - a.y * b.x;
}

let loopPhase = "";
let nextLoop = true;
function drawArtwork(t = 0) {
  clearCanvas();
  ctx.globalCompositeOperation = "source-over"; //"multiply";
  if (nextLoop && loopPhase === "disalignment") {
    nextLoop = false;
    // Randomise hexagon behaviour for next loop
    hexagonsData.forEach((shape, i) => {
      shape.disalignmentRate = Math.random() * 0.7 + 0.3;
      shape.disalignmentRate =
        Math.random() > 0.5 ? shape.disalignmentRate : -shape.disalignmentRate;
    });
  }
  if (t % 12000 < 6000) {
    loopPhase = "disalignment";
    // Disalign mirrors
    hexagonsData.forEach((shape, i) => {
      shape.normal += shape.disalignmentRate * 0.1;
    });
  } else {
    loopPhase = "alignment";
    nextLoop = true;
    // Align mirrors
    hexagonsData.forEach((shape, i) => {
      // Compute cursor angle from shape normal
      const dx = mouseX - shape.x;
      const dy = mouseY - shape.y;
      const dAngle = Math.atan2(dy, dx);
      const pointerAlignmentAngle = Math.atan2(
        Math.sin(dAngle - shape.normal),
        Math.cos(dAngle - shape.normal)
      );
      let targetPointerAngle = dAngle;
      let cp = cross(
        { x: dx, y: dy },
        { x: Math.cos(shape.normal), y: Math.sin(shape.normal) }
      );
      shape.normal += -cp * 0.00002;
    });
  }
  hexagonsData.forEach(drawHexagon);
  window.requestAnimationFrame(drawArtwork);
}

// Start the art
drawArtwork();

function drawHexagon(shape, tIndex) {
  const { x, y, normal, targetNormal, size, spin, tHueShift, rotation } = shape;
  // Increment shape orientation
  // Compute cursor angle from shape normal
  const dx = mouseX - x;
  const dy = mouseY - y;
  const dAngle = Math.atan2(dy, dx);
  const pointerAlignmentAngle = Math.abs(
    Math.atan2(Math.sin(dAngle - normal), Math.cos(dAngle - normal))
  );
  // shape.normal = dAngle;
  // Compute distance falloff factor
  const distance = Math.sqrt(dx ** 2 + dy ** 2);
  const lightPower = canvas.width * 1;
  const minDistanceFactor = 0.2;
  let distanceFactor = (lightPower - distance) / lightPower;
  // distanceFactor = distanceFactor < minDistanceFactor ? minDistanceFactor : distanceFactor;
  // Compute reflectance strength
  const pointerAlignmentDecimal = (Math.PI - pointerAlignmentAngle) / Math.PI;
  // const reflectanceStrength = (pointerAlignmentDecimal*0.2 + 0.8) * distanceFactor;
  const reflectanceStrength = pointerAlignmentDecimal ** 3 * 0.8 + 0.01;
  // Triangle path shape setup
  ctx.beginPath();
  const polygonSides = 6;
  const polyAngle = 1 / polygonSides;
  for (let i = 0; i < polygonSides; i++) {
    ctx.lineTo(
      x + size * Math.cos(rotation + TAU * i * polyAngle),
      y + size * Math.sin(rotation + TAU * i * polyAngle)
    );
  }
  ctx.closePath();
  // Fill shape
  // const hue = (pointerAlignmentAngle / Math.PI) * hueRange + hueShift + tHueShift;
  // const hue = (hueRange * (Math.abs(TAU*0.75 - shape.normal))/TAU) + hueShift;
  const hue = 50;
  const sauration = 100;
  const lightness = 100 * reflectanceStrength;
  const alpha = 1; //reflectanceStrength;
  ctx.fillStyle = `hsla(${hue},${sauration}%,${lightness}%,${alpha})`;
  ctx.fill();

  // Draw diagnostics
  const drawDiagnostics = false;
  if (drawDiagnostics) {
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(
      x + size * 0.5 * Math.cos(normal),
      y + size * 0.5 * Math.sin(normal)
    );
    ctx.closePath();
    ctx.strokeStyle = "red";
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(x, y, 2, 0, TAU);
    ctx.closePath();
    ctx.strokeStyle = "blue";
    ctx.stroke();
  }
}

// Pointer animation before interaction
let pointerLoopRAF;
function pointerLoop(t) {
  const radiusRatio = 1;
  const radius = canvas.width * radiusRatio;
  const rate = 0.0005;
  const x =
    canvas.width * radiusRatio * Math.cos(t * rate) + canvas.width * 0.5;
  const y =
    canvas.height * radiusRatio * Math.sin(t * rate) + canvas.height * 0.5;
  mouseX = x;
  mouseY = y;
  pointerLoopRAF = window.requestAnimationFrame(pointerLoop);
}
// pointerLoop();

// Interactions and Helper functions
canvas.addEventListener("touchmove", handleInteraction, false);
canvas.onmousemove = handleInteraction;

function handleInteraction(e) {
  // Stop the automated cursor animation
  window.cancelAnimationFrame(pointerLoopRAF);
  // Update global cursor coordinate variables
  const { x, y } = getMousePos(this, e);
  mouseX = x;
  mouseY = y;
}

function getMousePos(canvas, e) {
  let x;
  let y;
  if (
    e.type == "touchstart" ||
    e.type == "touchmove" ||
    e.type == "touchend" ||
    e.type == "touchcancel"
  ) {
    x = e.pageX;
    y = e.pageY;
  } else if (
    e.type == "mousedown" ||
    e.type == "mouseup" ||
    e.type == "mousemove" ||
    e.type == "mouseover" ||
    e.type == "mouseout" ||
    e.type == "mouseenter" ||
    e.type == "mouseleave"
  ) {
    const rect = canvas.getBoundingClientRect();
    // subtract the element's left and top position
    x = e.clientX - rect.left;
    y = e.clientY - rect.top;
  }
  return { x, y };
}

// Unused but useful and reference
function drawCoordinatePoints(points) {
  points.forEach(({ x, y }) => {
    ctx.beginPath();
    ctx.arc(x, y, 2, 0, TAU);
    ctx.strokeStyle = "black";
    ctx.stroke();
    ctx.closePath();
  });
}

const canvasGlobalCompositeOperationOptions = [
  "source-over",
  "source-atop",
  // "source-in",
  // "source-out",
  // "destination-over",
  // "destination-atop",
  // "destination-in",
  // "destination-out",
  // "lighter",
  // "copy",
  "xor",
  "multiply",
  "darken"
  // "lighten",
  // "screen", // 🤷‍
  // "color-dodge",
  // "color-burn", // 🤷‍
  // "hard-light",
  // "soft-light", // 🤷‍
  // "difference", // 🤮
  // "exclusion", // 🤮
  // "hue", // 🤷‍
  // "saturation", // 🤷‍
  // "color", // 🤷‍
  // "luminosity", // 🤮
  // "overlay", // 🤷‍
];

              
            
!
999px

Console