HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
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.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
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.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<footer class="footer v-dark">
Made with ☕ by <a class="footer-anchor" target="_blank" href="https://twitter.com/zadvorsky">Szenia</a>
</footer>
<div id="three-container"></div>
@import url('https://fonts.googleapis.com/css?family=Roboto');
$black: #343436;
$white: #fff;
$yellow: #fcd000;
*, *:before, *:after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body {
width: 100%;
height: 100%;
overflow: hidden;
cursor: move;
}
.footer {
position: fixed;
right: 0;
bottom: 0;
left: 0;
padding: 10px 10px;
text-align: right;
font-family: 'Roboto', sans-serif;
font-size: 12px;
&.v-dark {
background-color: $black;
color: $white;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
&.v-light {
background-color: $white;
color: $black;
}
}
.footer-anchor {
display: inline-block;
margin-left: 5px;
padding: 2px 4px;
color: $black;
text-decoration: none;
background-color: $yellow;
border-radius: 4px;
opacity: 1;
transition: opacity 0.2s;
&:hover {
opacity: 0.6;
}
}
// scene stuff
const root = new THREERoot({
createCameraControls: true,
zNear: 0.01,
zFar: 1000,
});
root.renderer.setClearColor(0x000000);
// root.controls.autoRotate = true;
// root.controls.autoRotateSpeed = -6;
root.camera.position.set(0, 0, 80);
root.scene.fog = new THREE.FogExp2(0xf1f1f1, 0.001);
const light = new THREE.DirectionalLight(0xffffff, 0.75);
light.position.set(1, 1, 1);
root.add(light);
const light2 = new THREE.DirectionalLight(0xffffff, 0.75);
light2.position.set(-1, 1, 1);
root.add(light2);
// text stuff
const string = 'CODEVEMBER';
const fontUrl = 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/175711/droid_sans_bold.typeface.js';
const fontParams = {
size: 12,
height: 1,
curveSegments: 1,
bevelEnabled: false,
bevelThickness: 1,
bevelSize: 1,
material: 0,
extrudeMaterial: 0,
letterSpacing: 200
};
new THREE.FontLoader().load(fontUrl, (font) => {
const letterMeshes = string.split('').map((letter) => {
return createLetterMesh(letter, font);
});
const letterGroup = new THREE.Group();
root.add(letterGroup);
let offsetX = 0;
letterMeshes.forEach((mesh, i) => {
letterGroup.add(mesh);
mesh.position.x = offsetX;
offsetX += mesh.userData.ha;
mesh.setColor(new THREE.Color().setHSL(i / letterMeshes.length, 1.0, 0.5));
});
const bounds = new THREE.Box3();
bounds.setFromObject(letterGroup);
const size = bounds.getSize();
letterGroup.position.x = -size.x * 0.5;
const v = new THREE.Vector3();
let t = 0;
root.addUpdateCallback(() => {
letterGroup.children.forEach((child, i) => {
v.copy(child.position);
v.y = (Math.sin((t + i) * 1.2)) * 5;
child.setPosition(v);
child.update();
t += (1/60);
});
});
});
function createLetterMesh(char, font) {
const geometry = new THREE.TextGeometry(char, {
font,
...fontParams
});
// geometry.center();
const modifier = new THREE.TessellateModifier(1);
for (let i = 0; i < 4; i++) {
modifier.modify(geometry);
}
const mesh = new FuzzyMesh({
geometry,
config: {
hairLength: 3,
hairRadiusBase: 0.3,
hairRadiusTop: 0.3,
hairRadialSegments: 4,
hairHeightSegments: 8,
fuzz: 2,
gravity: 4,
minForceFactor: 0.5,
maxForceFactor: 1.0,
movementForceFactor: 0.9
},
materialUniformValues: {
roughness: 0.4,
metalness: 0.1
}
});
const scale = fontParams.size / font.data.resolution;
const glyph = font.data.glyphs[char];
// todo: this doesn't feel like the correct way to calculate letter spacing
mesh.userData.ha = glyph.ha * scale + fontParams.letterSpacing * scale;
return mesh;
}
// Lib
/**
* Create a fuzzy mesh!
* @param params
* @constructor
*/
function FuzzyMesh(params) {
const config = this.config = {
recursiveRotation: true,
hairLength: 1,
hairRadialSegments: 3,
hairHeightSegments: 16,
hairRadiusTop: 0.0,
hairRadiusBase: 0.1,
minForceFactor: 1.0,
maxForceFactor: 1.0,
fuzz: 0.25,
gravity: 1.0,
centrifugalForceFactor: 1,
centrifugalDecay: 0.8,
movementForceFactor: 0.75,
movementDecay: 0.7,
settleDecay: 0.97, // should always be higher than movementDecay and centrifugal decay
...params.config
};
const materialUniformValues = {
metalness: 0.5,
roughness: 0.5,
...params.materialUniformValues
};
const positions = params.geometry.vertices;
// create a cone prefab for pointy hair
// create a cylinder prefab for non-pointy hair
let prefab;
if (config.hairRadiusTop === 0) {
prefab = new THREE.ConeGeometry(
config.hairRadiusBase,
config.hairLength,
config.hairRadialSegments,
config.hairHeightSegments,
true
);
}
else {
prefab = new THREE.CylinderGeometry(
config.hairRadiusTop,
config.hairRadiusBase,
config.hairLength,
config.hairRadialSegments,
config.hairHeightSegments,
false
);
}
// cone and cylinder geometries are created around the center
// translate them so the vertices start at y=0 and move up
prefab.translate(0, config.hairLength * 0.5, 0);
// create a geometry with 1 prefab per vertex of the supplied geometry
const geometry = new BAS.PrefabBufferGeometry(prefab, positions.length);
// forceFactor is a scalar that multiplies the total force affecting the vertex
geometry.createAttribute('forceFactor', 1, (data) => {
data[0] = THREE.Math.randFloat(config.minForceFactor, config.maxForceFactor);
});
// settleOffset is used to make sure the hair don't stop moving at the same time
geometry.createAttribute('settleOffset', 1, (data) => {
data[0] = THREE.Math.randFloat(0, Math.PI * 2);
});
// hair positions based on model vertices
geometry.createAttribute('hairPosition', 3, (data, i) => {
positions[i].toArray(data);
});
// hair directions
let directions;
if (params.directions) {
directions = params.directions;
}
// if params.directions is not set, we use vertex normals instead
else {
directions = [];
params.geometry.computeVertexNormals();
// get a flat array of vertex normals
for (let i = 0; i < params.geometry.faces.length; i++) {
const face = params.geometry.faces[i];
directions[face.a] = face.vertexNormals[0];
directions[face.b] = face.vertexNormals[1];
directions[face.c] = face.vertexNormals[2];
}
}
// base hair directions (which direction the hair goes with no force applied to it)
const direction = new THREE.Vector3();
geometry.createAttribute('baseDirection', 3, (data, i) => {
direction.copy(directions[i]);
direction.x += THREE.Math.randFloatSpread(config.fuzz);
direction.y += THREE.Math.randFloatSpread(config.fuzz);
direction.z += THREE.Math.randFloatSpread(config.fuzz);
direction.normalize();
direction.toArray(data);
});
const simpleShader = `
float f = position.y / HAIR_LENGTH;
vec3 totalForce = globalForce;
totalForce *= 1.0 - (sin(settleTime + settleOffset) * 0.05 * settleScale);
totalForce += hairPosition * centrifugalDirection * centrifugalForce;
totalForce *= forceFactor;
vec3 to = normalize(baseDirection + totalForce * f);
vec4 quat = quatFromUnitVectors(UP, to);
transformed = rotateVector(quat, transformed) + hairPosition;
`;
const recursiveShader = `
// accumulator for total force
vec3 totalForce = globalForce;
// add a little offset so the hairs don't all stop moving at the same time
// settleScale is increased when forces are applied, then gradually goes back to zero
totalForce *= 1.0 - (sin(settleTime + settleOffset) * 0.05 * settleScale);
// add force based on rotation
totalForce += hairPosition * centrifugalDirection * centrifugalForce;
// scale force based on a magic number!
totalForce *= forceFactor;
// accumulator for position
vec3 finalPosition = vec3(0.0, 0.0, 0.0);
// get height fraction between 0.0 and 1.0
float f = position.y / HAIR_LENGTH;
// determine target position based on force and height fraction
vec3 to = normalize(baseDirection + totalForce * f);
// calculate quaterion needed to rotate UP to target rotation
vec4 q = quatFromUnitVectors(UP, to);
// only apply this rotation to position x and z
// position y will be calculated in the loop below
vec3 v = vec3(position.x, 0.0, position.z);
finalPosition += rotateVector(q, v);
// recursively calculate rotations using the same approach as above
for (float i = 0.0; i < HAIR_LENGTH; i += SEGMENT_STEP) {
if (position.y <= i) break;
float f = i * FORCE_STEP;
vec3 to = normalize(baseDirection + totalForce * f);
vec4 q = quatFromUnitVectors(UP, to);
// apply this rotation to a 'segment'
vec3 v = vec3(0.0, SEGMENT_STEP, 0.0);
// all segments leading up to the Y position are added to the final position
finalPosition += rotateVector(q, v);
}
transformed = finalPosition + hairPosition;
`;
const material = new BAS.StandardAnimationMaterial({
flatShading: true,
wireframe: false,
uniformValues: materialUniformValues,
uniforms: {
hairLength: {value: config.hairLength},
settleTime: {value: 0.0},
settleScale: {value: 1.0},
globalForce: {value: new THREE.Vector3(0.0, -config.gravity, 0.0)},
centrifugalForce: {value: 0.0},
centrifugalDirection: {value: new THREE.Vector3(1, 0, 1).normalize()}
},
defines: {
'HAIR_LENGTH': (config.hairLength).toFixed(2),
'SEGMENT_STEP': (config.hairLength / config.hairHeightSegments).toFixed(2),
'FORCE_STEP': (1.0 / config.hairLength).toFixed(2)
},
vertexParameters: `
uniform float hairLength;
uniform float heightSteps;
uniform float heightStepSize;
uniform vec3 globalForce;
uniform float centrifugalForce;
uniform vec3 centrifugalDirection;
uniform float settleTime;
uniform float settleScale;
attribute float forceFactor;
attribute float settleOffset;
attribute vec3 hairPosition;
attribute vec3 baseDirection;
vec3 UP = vec3(0.0, 1.0, 0.0);
`,
vertexFunctions: [
BAS.ShaderChunk.quaternion_rotation,
`
// based on THREE.Quaternion.setFromUnitVectors
// would be great if we can get rid of the conditionals
vec4 quatFromUnitVectors(vec3 from, vec3 to) {
vec3 v = vec3(0.0, 0.0, 0.0);
float r = dot(from, to) + 1.0;
if (r < 0.00001) {
r = 0.0;
if (abs(from.x) > abs(from.z)) {
v.x = -from.y;
v.y = from.x;
v.z = 0.0;
}
else {
v.x = 0.0;
v.y = -from.z;
v.z = from.y;
}
}
else {
v = cross(from, to);
}
return normalize(vec4(v.xyz, r));
}
`
],
vertexPosition: config.recursiveRotation ? recursiveShader : simpleShader
});
THREE.Mesh.call(this, geometry, material);
// since the bounding box for the hair is never updated,
// set frustumCulled to false so the object doesn't disappear suddenly
this.frustumCulled = false;
// add the base geometry to self
this.baseMesh = new THREE.Mesh(
params.geometry,
new THREE.MeshStandardMaterial(materialUniformValues)
);
this.add(this.baseMesh);
// rotation stuff
this._quat = new THREE.Quaternion();
this.conjugate = new THREE.Quaternion();
this.rotationAxis = new THREE.Vector3(0, 1, 0);
this.angle = 0.0;
this.previousAngle = this.angle;
// position stuff
this.previousPosition = this.position.clone();
this.positionDelta = new THREE.Vector3();
this.movementForce = new THREE.Vector3();
}
FuzzyMesh.prototype = Object.create(THREE.Mesh.prototype);
FuzzyMesh.prototype.constructor = FuzzyMesh;
FuzzyMesh.prototype.setColor = function(color) {
this.baseMesh.material.color.set(color);
this.material.uniforms.diffuse.value.set(color);
};
FuzzyMesh.prototype.setPosition = function(position) {
this.previousPosition.copy(this.position);
this.position.copy(position);
};
FuzzyMesh.prototype.setRotationAngle = function(angle) {
this.previousAngle = this.angle;
this.angle = angle;
};
FuzzyMesh.prototype.setRotationAxis = function(axis) {
this.setRotationAngle(0);
const ra = this.rotationAxis;
const cd = this.material.uniforms.centrifugalDirection.value;
const q = this._quat;
// reset rotation axis and centrifugal direction;
ra.set(0, 1, 0);
cd.set(1, 0, 1);
// get angle between default rotation axis and target rotation axis
q.setFromUnitVectors(ra, axis);
// apply angle to centrifugal direction
cd.applyQuaternion(q);
// normalize the angle, and make the values absolute
cd.normalize();
cd.x = Math.abs(cd.x);
cd.y = Math.abs(cd.y);
cd.z = Math.abs(cd.z);
// finally don't forget to update the rotation axis
ra.copy(axis);
};
FuzzyMesh.prototype.update = function() {
// apply movement force
this.positionDelta.copy(this.previousPosition).sub(this.position);
this.movementForce.multiplyScalar(this.config.movementDecay);
this.movementForce.x += this.positionDelta.x * this.config.movementForceFactor;
this.movementForce.y += this.positionDelta.y * this.config.movementForceFactor;
this.movementForce.z += this.positionDelta.z * this.config.movementForceFactor;
this.material.uniforms.globalForce.value.set(
this.movementForce.x,
this.movementForce.y - this.config.gravity,
this.movementForce.z
);
this.previousPosition.copy(this.position);
// apply centrifugal force
const rotationSpeed = Math.abs(this.previousAngle - this.angle) % (Math.PI * 2);
this.material.uniforms.centrifugalForce.value *= this.config.centrifugalDecay;
this.material.uniforms.centrifugalForce.value += rotationSpeed * this.config.centrifugalForceFactor;
this.previousAngle = this.angle;
// adjust global force based on rotation
this.conjugate.copy(this.quaternion).conjugate();
this.material.uniforms.globalForce.value.applyQuaternion(this.conjugate);
// apply rotation to object
this.quaternion.setFromAxisAngle(this.rotationAxis, this.angle);
// rest / settle values
this.material.uniforms.settleTime.value += (1/10);
this.material.uniforms.settleScale.value *= this.config.settleDecay;
this.material.uniforms.settleScale.value += (this.movementForce.length() + rotationSpeed) * 0.1;
this.material.uniforms.settleScale.value > 1.0 && (this.material.uniforms.settleScale.value = 1.0);
};
// set the correct triangulate function for generating text geometries
THREE.ShapeUtils.triangulateShape = function ( contour, holes ) {
function removeDupEndPts( points ) {
var l = points.length;
if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
points.pop();
}
}
function addContour( vertices, contour ) {
for ( var i = 0; i < contour.length; i ++ ) {
vertices.push( contour[ i ].x );
vertices.push( contour[ i ].y );
}
}
removeDupEndPts( contour );
holes.forEach( removeDupEndPts );
var vertices = [];
addContour( vertices, contour );
var holeIndices = [];
var holeIndex = contour.length;
for ( i = 0; i < holes.length; i ++ ) {
holeIndices.push( holeIndex );
holeIndex += holes[ i ].length;
addContour( vertices, holes[ i ] );
}
var result = earcut( vertices, holeIndices, 2 );
var grouped = [];
for ( var i = 0; i < result.length; i += 3 ) {
grouped.push( result.slice( i, i + 3 ) );
}
return grouped;
};
Also see: Tab Triggers