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

              
                <script type="importmap">
  {
    "imports": {
      "three": "https://esm.sh/three@0.175.0/build/three.module.js",
      "three/addons/": "https://esm.sh/three@0.175.0/examples/jsm/"
    }
  }
</script>
              
            
!

CSS

              
                body{
  overflow: hidden;
  margin: 0;
}
              
            
!

JS

              
                import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";

console.clear();

class HelixCurve extends THREE.Curve {
  constructor(
    rBottom = 5,
    rTop = 7,
    yBottom = -7,
    yTop = 7,
    turns = 12,
    loose = 1,
    scale = 1
  ) {
    super();
    this.scale = scale;
    this.rBottom = rBottom;
    this.rTop = rTop;
    this.yBottom = yBottom;
    this.yTop = yTop;
    this.turns = turns;
    this.loose = loose;
  }

  getPoint(t, optionalTarget = new THREE.Vector3()) {
    let elevStart = this.yBottom;
    let elevation = (this.yTop - this.yBottom) * t ** this.loose;
    let radiusChange = (this.rTop - this.rBottom) * t + this.rBottom;
    let angleChagne = this.turns * Math.PI * 2 * t;

    return optionalTarget
      .set(
        Math.cos(angleChagne) * radiusChange,
        elevStart + elevation,
        Math.sin(-angleChagne) * radiusChange
      )
      .multiplyScalar(this.scale);
  }
}

class TubeGeometryExt extends THREE.BufferGeometry {
  constructor(
    path = new THREE.QuadraticBezierCurve3(
      new THREE.Vector3(-1, -1, 0),
      new THREE.Vector3(-1, 1, 0),
      new THREE.Vector3(1, 1, 0)
    ),
    tubularSegments = 64,
    radius = 1,
    radialSegments = 8,
    closed = false,
    capped = false,
    RGenerator = function (i, j) {
      return 1;
    }
  ) {
    super();

    this.type = "TubeGeometry";

    this.parameters = {
      path: path,
      tubularSegments: tubularSegments,
      radius: radius,
      radialSegments: radialSegments,
      closed: closed,
      capped: closed == true ? false : capped,
      RGenerator: RGenerator
    };

    const frames = path.computeFrenetFrames(tubularSegments, closed);

    // expose internals

    this.tangents = frames.tangents;
    this.normals = frames.normals;
    this.binormals = frames.binormals;

    // helper variables

    const vertex = new THREE.Vector3();
    const normal = new THREE.Vector3();
    const uv = new THREE.Vector2();
    let P = new THREE.Vector3();

    // buffer

    const vertices = [];
    const normals = [];
    const uvs = [];
    const indices = [];

    // create buffer data

    generateBufferData();

    // build geometry

    this.setIndex(indices);
    this.setAttribute(
      "position",
      new THREE.Float32BufferAttribute(vertices, 3)
    );
    this.setAttribute("normal", new THREE.Float32BufferAttribute(normals, 3));
    this.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
    this.computeVertexNormals();

    // correct seam normals
    let n1 = new THREE.Vector3();
    let n2 = new THREE.Vector3();
    let n = new THREE.Vector3();
    let nor = this.attributes.normal;
    for (let i = 0; i <= tubularSegments; i++) {
      let idx1 = i * (radialSegments + 1);
      let idx2 = i * (radialSegments + 1) + radialSegments;

      n1.fromBufferAttribute(nor, idx1);
      n2.fromBufferAttribute(nor, idx2);

      n.addVectors(n1, n2).multiplyScalar(0.5).normalize();

      nor.setXYZ(idx1, n.x, n.y, n.z);
      nor.setXYZ(idx2, n.x, n.y, n.z);
    }
    //////////////////////

    if (this.parameters.capped == true) {
      this.copy(
        mergeGeometries(
          [this, getCap(0, 0), getCap(this.parameters.tubularSegments + 1, 1)],
          true
        )
      );
    }

    // functions

    function getCap(segmentIndex, t) {
      let startIdx = segmentIndex * radialSegments;
      let endIdx = (segmentIndex + 1) * radialSegments;
      let verticesPart =
        t > 0
          ? vertices.slice(-(radialSegments + 1) * 3)
          : vertices.slice(0, (radialSegments + 1) * 3);

      let positions = [...path.getPointAt(t), ...verticesPart];

      let capG = new THREE.BufferGeometry();
      capG.setAttribute(
        "position",
        new THREE.Float32BufferAttribute(positions, 3)
      );

      let uvs = [0.5, 0.5];
      for (let iUV = 0; iUV <= radialSegments; iUV++) {
        let a = (iUV / radialSegments) * Math.PI * 2;
        uvs.push(Math.cos(a) * 0.5 + 0.5, Math.sin(a) * 0.5 + 0.5);
      }
      capG.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));

      let indices = Array.from({ length: radialSegments }, (_, idx) => {
        return [0, idx + 1, idx + 2];
      }).flat();

      if (segmentIndex != 0) {
        indices = indices.reverse();
      }
      capG.setIndex(indices);
      capG.computeVertexNormals();

      return capG;
    }

    function generateBufferData() {
      for (let i = 0; i < tubularSegments; i++) {
        generateSegment(i);
      }

      generateSegment(closed === false ? tubularSegments : 0);

      generateUVs();

      generateIndices();
    }

    function generateSegment(i) {
      P = path.getPointAt(i / tubularSegments, P);

      const N = frames.normals[i];
      const B = frames.binormals[i];

      for (let j = 0; j <= radialSegments; j++) {
        const v = (j / radialSegments) * Math.PI * 2;

        const sin = Math.sin(v);
        const cos = -Math.cos(v);

        let rScale = RGenerator(i / tubularSegments, v);

        normal.x = cos * N.x + sin * B.x;
        normal.y = cos * N.y + sin * B.y;
        normal.z = cos * N.z + sin * B.z;
        normal.normalize();
        normals.push(normal.x, normal.y, normal.z);

        vertex.x = P.x + radius * rScale * normal.x;
        vertex.y = P.y + radius * rScale * normal.y;
        vertex.z = P.z + radius * rScale * normal.z;
        vertices.push(vertex.x, vertex.y, vertex.z);
      }
    }

    function generateIndices() {
      for (let j = 1; j <= tubularSegments; j++) {
        for (let i = 1; i <= radialSegments; i++) {
          const a = (radialSegments + 1) * (j - 1) + (i - 1);
          const b = (radialSegments + 1) * j + (i - 1);
          const c = (radialSegments + 1) * j + i;
          const d = (radialSegments + 1) * (j - 1) + i;

          indices.push(a, b, d);
          indices.push(b, c, d);
        }
      }
    }

    function generateUVs() {
      for (let i = 0; i <= tubularSegments; i++) {
        for (let j = 0; j <= radialSegments; j++) {
          uv.x = i / tubularSegments;
          uv.y = j / radialSegments;

          uvs.push(uv.x, uv.y);
        }
      }
    }
  }
}

let gu = {
  time: {
    value: 0
  }
};
let dpr = Math.min(devicePixelRatio, 1);
let scene = new THREE.Scene();
scene.background = new THREE.Color(0xface8d);
let camera = new THREE.PerspectiveCamera(
  45,
  innerWidth / innerHeight,
  0.1,
  100
);
camera.position.set(0, 0.2, 1).setLength(32);
let renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth * dpr, innerHeight * dpr);
document.body.appendChild(renderer.domElement);

window.addEventListener("resize", (event) => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth * dpr, innerHeight * dpr);
});

let controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;

let light = new THREE.DirectionalLight(0xffffff, Math.PI * 1.5);
light.position.setScalar(1);
scene.add(light, new THREE.AmbientLight(0xffffff, Math.PI * 0.5));

// stuff
let glassCurves = [
  {
    curve: new HelixCurve(5, 8, -12, 7, 4, 1.25),
    color: "yellow",
    radius: 1,
    segmentation: 50,
    swaying: 10
  },
  {
    curve: new HelixCurve(8, 2, 7, 10, 2.5, 1),
    color: "white",
    radius: 0.75,
    segmentation: 30,
    swaying: 10
  },
  //J
  {
    curve: new THREE.CatmullRomCurve3(
      new THREE.CubicBezierCurve(
        new THREE.Vector2(-2, 5),
        new THREE.Vector2(-1, -5),
        new THREE.Vector2(-1, -5),
        new THREE.Vector2(-5, -5)
      )
        .getSpacedPoints(10)
        .map((p) => {
          return new THREE.Vector3(...p).setZ(0);
        })
    ),
    color: "maroon",
    radius: 0.75,
    segmentation: 10,
    swaying: 3
  },
  //S
  {
    curve: new THREE.CatmullRomCurve3(
      [
        [5, 5],
        [1, 2],
        [5, -2],
        [1, -5]
      ].map((p) => {
        return new THREE.Vector3(...p).setZ(0);
      }),
      false,
      "catmullrom",
      1
    ),
    color: "maroon",
    radius: 0.75,
    segmentation: 10,
    swaying: 3
  }
];

glassCurves.forEach((curve) => {
  let radiusCurve = new THREE.CatmullRomCurve3(
    Array.from({ length: curve.segmentation }, (_, idx) => {
      let r = (Math.random() * 0.75 + 0.25) * 1.5;
      r = idx == 0 || idx == curve.segmentation - 1 ? 0 : r;
      return new THREE.Vector3(idx, r, 0);
    })
  );

  let tubeCurve = curve.curve;

  let g = new TubeGeometryExt(
    tubeCurve,
    1000,
    curve.radius,
    100,
    false,
    false,

    function (i, j) {
      // [0..1], [0..2PI]
      let r = radiusCurve.getPoint(i).y;
      let swaying = Math.sin(Math.PI * 2 * curve.swaying * i) * Math.PI * 2;
      r *= Math.sin(j * 5 + swaying) * 0.5 + 0.5 + 0.5;
      return r;
    }
    /**/
  );
  let m = new THREE.MeshLambertMaterial({
    color: curve.color,
    wireframe: false
  });
  let o = new THREE.Mesh(g, m);
  o.position.y = 1;
  scene.add(o);
});

////////

let clock = new THREE.Clock();
let t = 0;

renderer.setAnimationLoop(() => {
  let dt = clock.getDelta();
  t += dt;
  gu.time.value = t;
  controls.update();

  renderer.render(scene, camera);
});

              
            
!
999px

Console