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.
<!--canvas id="testChars" style="position: absolute; margin: 10px; border: 1px solid aqua;"></canvas-->
body{
overflow: hidden;
margin: 0;
}
import * as THREE from "https://cdn.skypack.dev/three@0.136.0";
import { OrbitControls } from "https://cdn.skypack.dev/three@0.136.0/examples/jsm/controls/OrbitControls";
import * as BufferGeometryUtils from "https://cdn.skypack.dev/three@0.136.0/examples/jsm/utils/BufferGeometryUtils"
import { TWEEN } from "https://cdn.skypack.dev/three@0.136.0/examples/jsm/libs/tween.module.min";
console.clear();
let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.set(0, 0, 10);
let renderer = new THREE.WebGLRenderer({antialias: true});
//renderer.setClearColor(0x161616);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
window.addEventListener("resize", (event) => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
let controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.enablePan = false;
controls.minDistance = 8;
controls.maxDistance = 12;
controls.minPolarAngle = Math.PI * 0.5;
controls.maxPolarAngle = Math.PI * 0.5;
let light = new THREE.DirectionalLight(0xffffff, 0.5);
light.position.setScalar(1);
scene.add(light, new THREE.AmbientLight(0xffffff, 0.5));
let u = {
time: {value: 0}
}
let keyboard = makeKeyboard();
keyboard.position.x = -0.5;
keyboard.position.y = -2;
keyboard.rotation.x = -Math.PI / 5;
scene.add(keyboard);
let screenCanvas = document.createElement("canvas");
screenCanvas.width = screenCanvas.height = 128;
let screenTexture = new THREE.CanvasTexture(screenCanvas);
screenTexture.needsUpdate = true;
let screenPlane = new THREE.Mesh(new THREE.PlaneGeometry(4/3, 1), new THREE.MeshBasicMaterial({
color: 0x323232,
onBeforeCompile: shader => {
shader.uniforms.time = u.time;
shader.uniforms.glyphTex = new THREE.Uniform(screenTexture);
shader.fragmentShader = `
uniform float time;
uniform sampler2D glyphTex;
// from https://iquilezles.org/articles/distfunctions
float roundedBoxSDF(vec2 CenterPosition, vec2 Size, float Radius) {
return length(max(abs(CenterPosition)-Size+Radius,0.0))-Radius;
}
${shader.fragmentShader}
`.replace(
`#include <dithering_fragment>`,
`#include <dithering_fragment>
float ratio = 4./3.;
float box = roundedBoxSDF(vUv - vec2(0.5), vec2(0.5), 0.25);
if (box > 0.) discard;
float lines = sin((vUv.y + mod(time * 0.01, 100.)) * PI * 128.) * 0.5 + 0.5;
lines = pow(lines, 1.1);
vec2 uv = vUv * vec2(ratio, 1.) - vec2(fract(ratio) * 0.5, 0.);
float glyph = texture(glyphTex, uv).g;
gl_FragColor.rgb = mix(gl_FragColor.rgb + (0.1 * lines), vec3(0.25, 1, 0.75), glyph * lines);
`
);
//console.log(shader.fragmentShader)
}
}));
screenPlane.material.defines = {"USE_UV" : ""};
screenPlane.geometry.translate(0, 0.5, 0);
screenPlane.position.z = -50;
screenPlane.scale.setScalar(30);
scene.add(screenPlane);
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let intersects;
let isRunning = false;
window.addEventListener("pointerdown", event => {
pointer.x = ( event.clientX / window.innerWidth ) * 2 - 1;
pointer.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
intersects = raycaster.intersectObject(keyboard);
if (intersects.length > 0){
if (isRunning) return;
let arr = new Uint8Array(1).fill(0);
let keyId = Math.floor(intersects[0].faceIndex / 444); // 444 - amount of faces per part
new TWEEN.Tween({val: 0}).to({val: 1}, 62)
.repeat(1)
.yoyo(true)
.onStart( _ => {isRunning = true})
.onUpdate( val => {
let v = Math.round(val.val * 255);
arr[0] = v;
keyboard.userData.dataTex.image.data.set(arr, keyId);
}
)
.onComplete( _ => {isRunning = false})
.start();
showGlyph(keyId);
}
})
let clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
let t = clock.getElapsedTime();
u.time.value = t;
TWEEN.update();
controls.update();
keyboard.userData.dataTex.needsUpdate = true;
screenPlane.position.copy(camera.position).negate().setLength(55).add(camera.position);
screenPlane.quaternion.copy(camera.quaternion);
renderer.render(scene, camera);
});
function showGlyph(idx){
let ctx = screenCanvas.getContext("2d");
ctx.clearRect(0, 0, screenCanvas.width, screenCanvas.height);
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "bold 128px Arial";
ctx.fillStyle = "white";
let glyph = keyboard.userData.charMap.userData.str[idx];
ctx.fillText(glyph, screenCanvas.width * 0.5, screenCanvas.height * 0.5);
screenTexture.needsUpdate = true;
}
function makeKeyboard(){
let kGs = [];
makeLine(kGs, new THREE.Vector3(-5.25, 1.5, 0), new THREE.Vector3(1, 0, 0), 12);
makeLine(kGs, new THREE.Vector3(-4.75, 0.5, 0), new THREE.Vector3(1, 0, 0), 12);
makeLine(kGs, new THREE.Vector3(-4.5, -0.5, 0), new THREE.Vector3(1, 0, 0), 11);
makeLine(kGs, new THREE.Vector3(-4.0, -1.5, 0), new THREE.Vector3(1, 0, 0), 10);
let g = BufferGeometryUtils.mergeBufferGeometries(kGs, true);
//console.log(g);
let cm = createCharMap();
let m = new THREE.MeshLambertMaterial({
color: 0x323232,
onBeforeCompile: shader => {
shader.uniforms.indexMap = new THREE.Uniform(keyboard.userData.dataTex);
shader.uniforms.charMap = new THREE.Uniform(cm);
shader.vertexShader = `
uniform sampler2D indexMap;
attribute float blockIdx;
attribute vec2 blockUV;
varying float vBlockIdx;
varying vec2 vBlockUV;
varying float vShowSide;
varying float vZVal;
varying float vIdxVal;
${shader.vertexShader}
`.replace(
`#include <begin_vertex>`,
`#include <begin_vertex>
float xIdxStep = 1. / ${kGs.length}.;
float idxVal = texture2D(indexMap, vec2((blockIdx + 0.5) * xIdxStep, 0.5)).r;
vIdxVal = idxVal;
transformed.z = position.z - (0.2 * idxVal);
vBlockIdx = blockIdx;
vBlockUV = blockUV;
vShowSide = step(0.05, position.z);
vZVal = position.z;
`
);
//console.log(shader.vertexShader);
shader.fragmentShader = `
#define ss(a, b, c) smoothstep(a, b ,c)
uniform sampler2D charMap;
varying float vBlockIdx;
varying vec2 vBlockUV;
varying float vShowSide;
varying float vZVal;
varying float vIdxVal;
${shader.fragmentShader}
`.replace(
`#include <dithering_fragment>`,
`#include <dithering_fragment>
gl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(1), vIdxVal);
float charStep = 1. / 8.;
vec2 sumUV = vBlockUV + clamp((vUv - 0.25 * charStep) * 2., 0., charStep);
float charValue = texture2D(charMap, sumUV).g;
gl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(1, 0, 0), charValue * vShowSide); // glyph
float fw = fwidth(vZVal) * 2.;
float midLine = ss(0.0125 - fw, 0.0125, vZVal) - ss(0.025, 0.025 + fw , vZVal);
gl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(1, 0, 0), midLine); // red border
`
);
//console.log(shader.fragmentShader);
}
});
m.defines = {"USE_UV": ""};
let keys = new THREE.Mesh(g, m);
keys.userData = {
dataTex: createDataTexture(kGs.length),
charMap: cm
}
return keys;
}
function createDataTexture(len){
let data = new Uint8Array(len).fill(0);
let texture = new THREE.DataTexture(data, len, 1);
texture.format = THREE.RedFormat;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.unpackAlignment = 1;
texture.needsUpdate = true;
return texture;
}
function makeLine(keysArray, startPos, stepPos, keysInLine){
let startIdx = keysArray.length;
for(let i = 0; i < keysInLine; i++){
let keyG = makeKey({x: 0.4, y: 0.4}, startIdx + i);
keyG.translate(
startPos.x + stepPos.x * i,
startPos.y + stepPos.y * i,
startPos.z + stepPos.z * i
);
keysArray.push(keyG);
}
}
function makeKey(halfSize, idx){
const r = 0.1;
const h = 0.05;
const x = halfSize.x - r;
const y = halfSize.y - r;
let shape = new THREE.Shape()
.absarc( x, y, r, Math.PI * 0.5 * 0, Math.PI * 0.5 * 1)
.absarc(-x, y, r, Math.PI * 0.5 * 1, Math.PI * 0.5 * 2)
.absarc(-x, -y, r, Math.PI * 0.5 * 2, Math.PI * 0.5 * 3)
.absarc( x, -y, r, Math.PI * 0.5 * 3, Math.PI * 0.5 * 4)
let g = new THREE.ExtrudeGeometry(shape, {
depth: h,
curveSegments: 3,
bevelEnabled: true,
bevelSize: 0.05,
bevelThickness: 0.05,
bevelSegments: 3
});
g.groups = null;
let pos = g.attributes.position;
let uvs = g.attributes.uv;
let v3 = new THREE.Vector3();
const count = 8.;
const charStep = 1./ count;
const blockY = Math.floor(idx / count);
const blockX = idx % count;
//console.log(blockX, blockY);
let blockUVx = blockX * charStep;
let blockUVy = (count - 1. - blockY) * charStep;
//console.log(blockUVx, blockUVy);
let blockUV = [];
let blockIdx = [];
//console.log(pos.count / 3);
for(let i = 0; i < pos.count; i++){
v3.fromBufferAttribute(pos, i);
let charUVx = (v3.x - -halfSize.x) / (halfSize.x * 2);
let charUVy = (v3.y - -halfSize.y) / (halfSize.y * 2);
uvs.setXY(i, charUVx * charStep, charUVy * charStep);
blockUV.push(blockUVx, blockUVy);
blockIdx.push(idx);
}
g.setAttribute("blockUV", new THREE.Float32BufferAttribute(blockUV, 2));
g.setAttribute("blockIdx", new THREE.Float32BufferAttribute(blockIdx, 1));
return g;
}
function createCharMap(){
//let c = document.getElementById("testChars");
let c = document.createElement("canvas");
const size = 1024;
const segs = 8;
c.width = c.height = size;
let step = size / segs;
let hStep = step * 0.5;
let ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "bold 96px Arial";
ctx.fillStyle = "white";
let str = "1234567890-=QWERTYUIOP[]ASDFGHJKL;'ZXCVBNM,./".split('');
str.forEach( (char, idx) => {
let y = Math.floor(idx / segs);
let x = idx % segs;
let posX = (x + 0.5) * step;
let posY = (y + 0.5) * step;
ctx.fillText(char, posX, posY);
});
let tex = new THREE.CanvasTexture(c);
tex.userData = {
str: str
}
tex.needsUpdate = true;
return tex;
}
Also see: Tab Triggers