Prompt specification
Build or customize the Three.js 3D scene "Bezier curve control-point frame" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Bezier curve control-point frame
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/bezier-curve-control-point-frame-x1713
Scene Description Prompt:
Make a low-poly cubic Bézier explorer with four movable controls, construction lines, and endpoint tangents. One HTML file using Three.js from cdnjs.
Working Three.js Starter (bezier-curve-control-point-frame-x1713):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Cubic Bézier Explorer</title>
<style>
:root {
color-scheme: light;
--ink: #17324d;
--muted: #687582;
--paper: rgba(250, 248, 242, 0.88);
--line: rgba(23, 50, 77, 0.13);
--teal: #1b998b;
--orange: #ef8354;
--red: #d95742;
--gold: #f2c14e;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #f3efe6;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
#viewport,
#labels {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
#labels {
z-index: 3;
pointer-events: none;
overflow: hidden;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: 18px;
background: var(--paper);
box-shadow:
0 16px 50px rgba(31, 48, 61, 0.13),
inset 0 0 0 1px var(--line);
backdrop-filter: blur(14px) saturate(120%);
-webkit-backdrop-filter: blur(14px) saturate(120%);
}
.main-panel {
top: 18px;
left: 18px;
width: 330px;
padding: 19px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
color: var(--teal);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
width: 7px;
height: 7px;
border-radius: 2px;
background: var(--teal);
content: "";
transform: rotate(45deg);
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(27px, 3vw, 37px);
font-weight: 500;
line-height: 0.98;
letter-spacing: -0.035em;
}
.intro {
margin: 11px 0 15px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.toggles {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
padding: 11px 0 14px;
border-top: 1px solid var(--line);
border-bottom: 1px solid var(--line);
}
.toggle {
display: flex;
align-items: center;
gap: 7px;
color: #435464;
font-size: 11px;
cursor: pointer;
user-select: none;
}
.toggle input {
width: 14px;
height: 14px;
margin: 0;
accent-color: var(--teal);
}
.actions {
display: flex;
gap: 7px;
margin-top: 13px;
}
button {
min-height: 34px;
padding: 0 12px;
border: 1px solid rgba(23, 50, 77, 0.16);
border-radius: 10px;
background: rgba(255, 255, 255, 0.62);
color: var(--ink);
font-size: 11px;
font-weight: 700;
cursor: pointer;
transition:
transform 120ms ease,
background 120ms ease,
border-color 120ms ease;
}
button:hover {
border-color: rgba(23, 50, 77, 0.3);
background: #fff;
transform: translateY(-1px);
}
button:active { transform: translateY(0); }
.inspector-panel {
top: 18px;
right: 18px;
width: 270px;
padding: 17px;
}
.panel-title {
margin: 0 0 13px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.selected-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
#selectedName {
font-family: Georgia, "Times New Roman", serif;
font-size: 28px;
}
#derivative {
max-width: 145px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
text-align: right;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.42);
}
.metric span {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric strong {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
font-weight: 650;
}
.divider {
height: 1px;
margin: 14px 0 12px;
background: var(--line);
}
.tangent-row {
display: grid;
grid-template-columns: 26px 1fr auto;
align-items: center;
gap: 8px;
min-height: 31px;
color: var(--muted);
font-size: 10px;
}
.tangent-row strong {
color: var(--red);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
.tangent-row .magnitude {
color: #82909b;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
}
.sample-panel {
left: 50%;
bottom: 18px;
width: min(450px, calc(100vw - 36px));
padding: 12px 15px;
transform: translateX(-50%);
}
.sample-top {
display: flex;
align-items: center;
gap: 13px;
}
.sample-title {
flex: 0 0 auto;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
#tSlider {
width: 100%;
accent-color: var(--orange);
cursor: pointer;
}
#tValue {
min-width: 34px;
color: var(--orange);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
font-weight: 700;
text-align: right;
}
.sample-coordinate {
margin-top: 8px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
text-align: right;
}
.point-label,
.tangent-label {
position: absolute;
display: none;
white-space: nowrap;
transform: translate(-50%, -50%);
user-select: none;
}
.point-label {
padding: 4px 7px;
border: 1px solid rgba(255, 255, 255, 0.85);
border-radius: 8px;
background: rgba(250, 248, 242, 0.92);
box-shadow: 0 4px 13px rgba(23, 50, 77, 0.13);
color: var(--ink);
font-size: 11px;
font-weight: 800;
}
.point-label.endpoint { color: var(--teal); }
.point-label.handle { color: #cf6840; }
.point-label.selected {
border-color: rgba(23, 50, 77, 0.28);
box-shadow:
0 4px 13px rgba(23, 50, 77, 0.13),
0 0 0 2px rgba(23, 50, 77, 0.08);
}
.tangent-label {
color: var(--red);
font-family: Georgia, "Times New Roman", serif;
font-size: 13px;
font-style: italic;
font-weight: 700;
text-shadow: 0 1px 5px #fff;
}
.zoom-controls {
position: fixed;
right: 18px;
bottom: 18px;
z-index: 12;
display: flex;
gap: 5px;
padding: 5px;
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: 13px;
background: var(--paper);
box-shadow: 0 10px 30px rgba(31, 48, 61, 0.12);
backdrop-filter: blur(12px);
}
.zoom-controls button {
width: 34px;
min-height: 32px;
padding: 0;
font-size: 18px;
}
.help {
position: fixed;
left: 18px;
bottom: 18px;
z-index: 9;
padding: 8px 10px;
border-radius: 10px;
background: rgba(250, 248, 242, 0.72);
color: #71808c;
font-size: 9px;
letter-spacing: 0.02em;
backdrop-filter: blur(8px);
}
@media (max-width: 760px) {
.main-panel {
top: 10px;
left: 10px;
width: min(300px, calc(100vw - 20px));
padding: 15px;
}
.inspector-panel {
top: 10px;
right: 10px;
width: 225px;
padding: 13px;
}
.intro { display: none; }
.help { display: none; }
}
@media (max-width: 570px) {
.main-panel { width: calc(100vw - 20px); }
.inspector-panel { display: none; }
.sample-panel { bottom: 10px; }
.zoom-controls { right: 10px; bottom: 78px; }
}
</style>
</head>
<body>
<div id="viewport"></div>
<div id="labels"></div>
<section class="panel main-panel">
<div class="eyebrow">Interactive geometry</div>
<h1>Cubic Bézier<br />Explorer</h1>
<p class="intro">
Drag any diamond to reshape the curve. The dashed control polygon,
endpoint tangents, and sampled point update in real time.
</p>
<div class="toggles">
<label class="toggle">
<input id="constructionToggle" type="checkbox" checked />
Construction
</label>
<label class="toggle">
<input id="tangentToggle" type="checkbox" checked />
Tangents
</label>
<label class="toggle">
<input id="labelsToggle" type="checkbox" checked />
Labels
</label>
<label class="toggle">
<input id="gridToggle" type="checkbox" checked />
Grid
</label>
</div>
<div class="actions">
<button id="resetButton" type="button">Reset curve</button>
<button id="shuffleButton" type="button">Shuffle</button>
<button id="viewButton" type="button">Reset view</button>
</div>
</section>
<section class="panel inspector-panel">
<h2 class="panel-title">Curve inspector</h2>
<div class="selected-row">
<strong id="selectedName">P₀</strong>
<span id="derivative">3(P₁ − P₀)</span>
</div>
<div class="metrics">
<div class="metric">
<span>X</span>
<strong id="selectedX">−3.10</strong>
</div>
<div class="metric">
<span>Y</span>
<strong id="selectedY">−1.40</strong>
</div>
</div>
<div class="divider"></div>
<h2 class="panel-title">Endpoint tangents</h2>
<div class="tangent-row">
<strong>T₀</strong>
<span>angle / length</span>
<span><b id="tangent0">0°</b> <span class="magnitude" id="magnitude0"></span></span>
</div>
<div class="tangent-row">
<strong>T₃</strong>
<span>angle / length</span>
<span><b id="tangent3">0°</b> <span class="magnitude" id="magnitude3"></span></span>
</div>
</section>
<section class="panel sample-panel">
<div class="sample-top">
<span class="sample-title">Sample t</span>
<input id="tSlider" type="range" min="0" max="1" step="0.001" value="0.42" />
<span id="tValue">0.42</span>
</div>
<div class="sample-coordinate" id="sampleCoordinate">B(t) = (0.00, 0.00)</div>
</section>
<div class="zoom-controls">
<button id="zoomOut" type="button" aria-label="Zoom out">−</button>
<button id="zoomIn" type="button" aria-label="Zoom in">+</button>
</div>
<div class="help">Drag blank space to orbit · Right-drag to pan · Scroll to zoom · Arrow keys nudge</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = document.getElementById("viewport");
const labelsRoot = document.getElementById("labels");
const $ = (id) => document.getElementById(id);
const COLORS = {
background: 0xf3efe6,
ground: 0xf3efe6,
curve: 0x17324d,
endpoint: 0x1b998b,
handle: 0xef8354,
tangent: 0xd95742,
sample: 0xf2c14e,
gridMajor: 0xc9c2b6,
gridMinor: 0xded8cd
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(COLORS.background);
scene.fog = new THREE.Fog(COLORS.background, 19, 38);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("aria-label", "Interactive cubic Bézier curve");
viewport.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
42,
viewport.clientWidth / viewport.clientHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 0, 0);
const defaultCameraPosition = new THREE.Vector3(6.6, 5.4, 10.5);
camera.position.copy(defaultCameraPosition);
camera.lookAt(cameraTarget);
const hemisphere = new THREE.HemisphereLight(0xffffff, 0xa18c73, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff4df, 3.1);
sun.position.set(4, 7, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -9;
sun.shadow.camera.right = 9;
sun.shadow.camera.top = 9;
sun.shadow.camera.bottom = -9;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.0005;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xcce7ef, 1.0);
fill.position.set(-6, -2, 5);
scene.add(fill);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
new THREE.MeshStandardMaterial({
color: COLORS.ground,
roughness: 1,
metalness: 0
})
);
ground.position.z = -0.28;
ground.receiveShadow = true;
scene.add(ground);
const gridGroup = new THREE.Group();
scene.add(gridGroup);
const grid = new THREE.GridHelper(14, 14, COLORS.gridMajor, COLORS.gridMinor);
grid.rotation.x = Math.PI / 2;
grid.position.z = -0.255;
grid.material.transparent = true;
grid.material.opacity = 0.48;
gridGroup.add(grid);
const xAxis = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-6, 0, -0.245),
new THREE.Vector3(6, 0, -0.245)
]),
new THREE.LineBasicMaterial({
color: 0x9eb0b7,
transparent: true,
opacity: 0.45
})
);
const yAxis = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, -4, -0.245),
new THREE.Vector3(0, 4, -0.245)
]),
new THREE.LineBasicMaterial({
color: 0x9eb0b7,
transparent: true,
opacity: 0.45
})
);
gridGroup.add(xAxis, yAxis);
const CONTROL_Z = 0.18;
const defaultPoints = [
new THREE.Vector3(-3.1, -1.4, CONTROL_Z),
new THREE.Vector3(-2.35, 2.05, CONTROL_Z),
new THREE.Vector3(1.55, 2.35, CONTROL_Z),
new THREE.Vector3(3.2, -1.45, CONTROL_Z)
];
const points = defaultPoints.map((point) => point.clone());
const pointNames = ["P₀", "P₁", "P₂", "P₃"];
const pointRoles = ["start", "handle", "handle", "end"];
const derivativeEquations = [
"3(P₁ − P₀)",
"3(P₀ − 2P₁ + P₂)",
"3(P₁ − 2P₂ + P₃)",
"3(P₃ − P₂)"
];
class CubicBezierCurve extends THREE.Curve {
constructor(controlPoints) {
super();
this.controlPoints = controlPoints;
}
getPoint(t, target = new THREE.Vector3()) {
const [p0, p1, p2, p3] = this.controlPoints;
const u = 1 - t;
const u2 = u * u;
const t2 = t * t;
target.set(
u2 * u * p0.x +
3 * u2 * t * p1.x +
3 * u * t2 * p2.x +
t2 * t * p3.x,
u2 * u * p0.y +
3 * u2 * t * p1.y +
3 * u * t2 * p2.y +
t2 * t * p3.y,
CONTROL_Z
);
return target;
}
getTangent(t, target = new THREE.Vector3()) {
const [p0, p1, p2, p3] = this.controlPoints;
const u = 1 - t;
target.set(
3 * u * u * (p1.x - p0.x) +
6 * u * t * (p2.x - p1.x) +
3 * t * t * (p3.x - p2.x),
3 * u * u * (p1.y - p0.y) +
6 * u * t * (p2.y - p1.y) +
3 * t * t * (p3.y - p2.y),
0
);
return target;
}
}
const bezier = new CubicBezierCurve(points);
// Builds a faceted, four-sided tube without using any external examples.
function createLowPolyTube(curve, tubularSegments = 144, radialSegments = 4, radius = 0.075) {
const positions = [];
const indices = [];
const center = new THREE.Vector3();
const tangent = new THREE.Vector3();
const normal = new THREE.Vector3();
const binormal = new THREE.Vector3();
const vertex = new THREE.Vector3();
for (let i = 0; i <= tubularSegments; i++) {
const t = i / tubularSegments;
curve.getPoint(t, center);
curve.getTangent(t, tangent).normalize();
normal.set(-tangent.y, tangent.x, 0);
if (normal.lengthSq() < 0.000001) {
normal.set(1, 0, 0);
} else {
normal.normalize();
}
binormal.crossVectors(tangent, normal).normalize();
for (let j = 0; j < radialSegments; j++) {
const angle = (j / radialSegments) * Math.PI * 2;
vertex
.copy(center)
.addScaledVector(normal, Math.cos(angle) * radius)
.addScaledVector(binormal, Math.sin(angle) * radius);
positions.push(vertex.x, vertex.y, vertex.z);
}
}
for (let i = 0; i < tubularSegments; i++) {
for (let j = 0; j < radialSegments; j++) {
const a = i * radialSegments + j;
const b = i * radialSegments + ((j + 1) % radialSegments);
const c = (i + 1) * radialSegments + j;
const d = (i + 1) * radialSegments + ((j + 1) % radialSegments);
indices.push(a, b, c, b, d, c);
}
}
const indexed = new THREE.BufferGeometry();
indexed.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
indexed.setIndex(indices);
const flat = indexed.toNonIndexed();
indexed.dispose();
flat.computeVertexNormals();
flat.computeBoundingSphere();
return flat;
}
const curveMaterial = new THREE.MeshStandardMaterial({
color: COLORS.curve,
roughness: 0.72,
metalness: 0.04,
flatShading: true
});
const curveMesh = new THREE.Mesh(
createLowPolyTube(bezier),
curveMaterial
);
curveMesh.castShadow = true;
curveMesh.receiveShadow = true;
scene.add(curveMesh);
const pointMeshes = [];
const pointLabels = [];
const selectionRings = [];
const pointGeometry = new THREE.OctahedronGeometry(0.19, 0);
points.forEach((point, index) => {
const isEndpoint = index === 0 || index === 3;
const color = isEndpoint ? COLORS.endpoint : COLORS.handle;
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.06,
roughness: 0.62,
metalness: 0.05,
flatShading: true
});
const mesh = new THREE.Mesh(pointGeometry, material);
mesh.position.copy(point);
mesh.scale.setScalar(isEndpoint ? 1.15 : 1);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData.pointIndex = index;
scene.add(mesh);
pointMeshes.push(mesh);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.3, 0.017, 4, 28),
new THREE.MeshBasicMaterial({
color: 0x17324d,
transparent: true,
opacity: 0.72,
depthTest: false
})
);
ring.position.copy(point);
ring.position.z += 0.015;
ring.renderOrder = 9;
ring.visible = false;
scene.add(ring);
selectionRings.push(ring);
const label = document.createElement("div");
label.className = `point-label ${isEndpoint ? "endpoint" : "handle"}`;
label.textContent = pointNames[index];
labelsRoot.appendChild(label);
pointLabels.push(label);
});
const constructionGroup = new THREE.Group();
scene.add(constructionGroup);
const polygonLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: 0x617c89,
dashSize: 0.15,
gapSize: 0.095,
transparent: true,
opacity: 0.85,
depthTest: false
})
);
polygonLine.renderOrder = 5;
const chordLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: 0x9ca7ae,
dashSize: 0.065,
gapSize: 0.105,
transparent: true,
opacity: 0.8,
depthTest: false
})
);
chordLine.renderOrder = 4;
constructionGroup.add(polygonLine, chordLine);
const tangentGroup = new THREE.Group();
scene.add(tangentGroup);
const tangentMaterial = new THREE.LineDashedMaterial({
color: COLORS.tangent,
dashSize: 0.13,
gapSize: 0.075,
transparent: true,
opacity: 0.9,
depthTest: false
});
const tangentLine0 = new THREE.Line(
new THREE.BufferGeometry(),
tangentMaterial
);
const tangentLine3 = new THREE.Line(
new THREE.BufferGeometry(),
tangentMaterial.clone()
);
tangentLine0.renderOrder = 6;
tangentLine3.renderOrder = 6;
const arrowGeometry = new THREE.ConeGeometry(0.105, 0.27, 5, 1, false);
const tangentHead0 = new THREE.Mesh(
arrowGeometry,
new THREE.MeshBasicMaterial({
color: COLORS.tangent,
depthTest: false
})
);
const tangentHead3 = new THREE.Mesh(
arrowGeometry.clone(),
new THREE.MeshBasicMaterial({
color: COLORS.tangent,
depthTest: false
})
);
tangentHead0.renderOrder = 7;
tangentHead3.renderOrder = 7;
tangentGroup.add(tangentLine0, tangentLine3, tangentHead0, tangentHead3);
const tangentLabel0 = document.createElement("div");
tangentLabel0.className = "tangent-label";
tangentLabel0.textContent = "T₀";
const tangentLabel3 = document.createElement("div");
tangentLabel3.className = "tangent-label";
tangentLabel3.textContent = "T₃";
labelsRoot.append(tangentLabel0, tangentLabel3);
const sampleMarker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.135, 0),
new THREE.MeshStandardMaterial({
color: COLORS.sample,
emissive: 0x9c6e00,
emissiveIntensity: 0.22,
roughness: 0.55,
flatShading: true
})
);
sampleMarker.castShadow = true;
scene.add(sampleMarker);
let selectedIndex = 0;
let tValue = Number($("tSlider").value);
let labelsEnabled = true;
function formatNumber(value) {
const clean = Math.abs(value) < 0.0005 ? 0 : value;
return clean.toFixed(2).replace("-", "−");
}
function setLinePoints(line, linePoints) {
line.geometry.dispose();
line.geometry = new THREE.BufferGeometry().setFromPoints(linePoints);
line.computeLineDistances();
}
const upAxis = new THREE.Vector3(0, 1, 0);
function updateTangent(line, head, origin, direction) {
const dir = direction.clone();
if (dir.lengthSq() < 0.000001) {
dir.set(1, 0, 0);
} else {
dir.normalize();
}
const back = origin.clone().addScaledVector(dir, -0.9);
const front = origin.clone().addScaledVector(dir, 1.9);
setLinePoints(line, [back, front]);
head.position.copy(origin).addScaledVector(dir, 0.57);
head.quaternion.setFromUnitVectors(upAxis, dir);
}
function rebuildCurveGeometry() {
const oldGeometry = curveMesh.geometry;
curveMesh.geometry = createLowPolyTube(bezier);
oldGeometry.dispose();
}
function updateSampleMarker() {
bezier.getPoint(tValue, sampleMarker.position);
}
function angleDegrees(direction) {
let angle = Math.atan2(direction.y, direction.x) * 180 / Math.PI;
if (angle < 0) angle += 360;
return angle;
}
function updateInspector() {
const selected = points[selectedIndex];
$("selectedName").textContent = `${pointNames[selectedIndex]} · ${pointRoles[selectedIndex]}`;
$("derivative").textContent = derivativeEquations[selectedIndex];
$("selectedX").textContent = formatNumber(selected.x);
$("selectedY").textContent = formatNumber(selected.y);
const d0 = points[1].clone().sub(points[0]);
const d3 = points[3].clone().sub(points[2]);
$("tangent0").textContent = `${angleDegrees(d0).toFixed(1)}°`;
$("tangent3").textContent = `${angleDegrees(d3).toFixed(1)}°`;
$("magnitude0").textContent = `| ${(d0.length() * 3).toFixed(2)}`;
$("magnitude3").textContent = `| ${(d3.length() * 3).toFixed(2)}`;
const sample = bezier.getPoint(tValue);
$("tValue").textContent = tValue.toFixed(2);
$("sampleCoordinate").textContent =
`B(t) = (${formatNumber(sample.x)}, ${formatNumber(sample.y)})`;
}
function selectPoint(index) {
selectedIndex = index;
pointLabels.forEach((label, i) => {
label.classList.toggle("selected", i === selectedIndex);
});
pointMeshes.forEach((mesh, i) => {
mesh.material.emissiveIntensity = i === selectedIndex ? 0.28 : 0.06;
});
updateInspector();
}
function updateGeometry() {
points.forEach((point, index) => {
pointMeshes[index].position.copy(point);
selectionRings[index].position.copy(point);
selectionRings[index].position.z += 0.015;
});
setLinePoints(polygonLine, points);
setLinePoints(chordLine, [points[0], points[3]]);
updateTangent(
tangentLine0,
tangentHead0,
points[0],
points[1].clone().sub(points[0])
);
updateTangent(
tangentLine3,
tangentHead3,
points[3],
points[3].clone().sub(points[2])
);
rebuildCurveGeometry();
updateSampleMarker();
updateInspector();
}
function placeLabel(element, worldPosition, offsetX = 0, offsetY = 0, visible = true) {
if (!visible) {
element.style.display = "none";
return;
}
const projected = worldPosition.clone().project(camera);
if (projected.z < -1 || projected.z > 1) {
element.style.display = "none";
return;
}
const width = viewport.clientWidth;
const height = viewport.clientHeight;
const x = (projected.x * 0.5 + 0.5) * width + offsetX;
const y = (-projected.y * 0.5 + 0.5) * height + offsetY;
element.style.display = "block";
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function updateLabelPositions() {
const offsets = [
[-20, 20],
[-13, -25],
[16, 21],
[20, -18]
];
points.forEach((point, index) => {
placeLabel(
pointLabels[index],
point,
offsets[index][0],
offsets[index][1],
labelsEnabled
);
});
const d0 = points[1].clone().sub(points[0]).normalize();
const d3 = points[3].clone().sub(points[2]).normalize();
placeLabel(
tangentLabel0,
points[0].clone().addScaledVector(d0, 1.0),
0,
-13,
labelsEnabled && tangentGroup.visible
);
placeLabel(
tangentLabel3,
points[3].clone().addScaledVector(d3, 1.0),
0,
-13,
labelsEnabled && tangentGroup.visible
);
}
function syncVisibility() {
constructionGroup.visible = $("constructionToggle").checked;
tangentGroup.visible = $("tangentToggle").checked;
gridGroup.visible = $("gridToggle").checked;
labelsEnabled = $("labelsToggle").checked;
}
$("constructionToggle").addEventListener("change", syncVisibility);
$("tangentToggle").addEventListener("change", syncVisibility);
$("labelsToggle").addEventListener("change", syncVisibility);
$("gridToggle").addEventListener("change", syncVisibility);
$("tSlider").addEventListener("input", () => {
tValue = Number($("tSlider").value);
updateSampleMarker();
updateInspector();
});
$("resetButton").addEventListener("click", () => {
defaultPoints.forEach((point, index) => points[index].copy(point));
tValue = 0.42;
$("tSlider").value = String(tValue);
selectPoint(0);
updateGeometry();
});
function randomBetween(min, max) {
return min + Math.random() * (max - min);
}
$("shuffleButton").addEventListener("click", () => {
points[0].set(randomBetween(-4.0, -2.5), randomBetween(-2.2, 2.2), CONTROL_Z);
points[1].set(randomBetween(-3.4, 1.2), randomBetween(-2.2, 2.2), CONTROL_Z);
points[2].set(randomBetween(-1.2, 3.4), randomBetween(-2.2, 2.2), CONTROL_Z);
points[3].set(randomBetween(2.5, 4.0), randomBetween(-2.2, 2.2), CONTROL_Z);
updateGeometry();
});
$("viewButton").addEventListener("click", () => {
cameraTarget.set(0, 0, 0);
camera.position.copy(defaultCameraPosition);
camera.lookAt(cameraTarget);
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(
new THREE.Vector3(0, 0, 1),
-CONTROL_Z
);
const planeHit = new THREE.Vector3();
let dragState = null;
function setPointerFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
event.preventDefault();
renderer.domElement.setPointerCapture(event.pointerId);
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(pointMeshes, false);
if (hits.length && event.button === 0) {
const index = hits[0].object.userData.pointIndex;
selectPoint(index);
dragState = {
type: "point",
index,
pointerId: event.pointerId
};
} else {
dragState = {
type: event.button === 2 ? "pan" : "orbit",
pointerId: event.pointerId,
lastX: event.clientX,
lastY: event.clientY
};
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragState || dragState.pointerId !== event.pointerId) return;
const dx = event.clientX - dragState.lastX;
const dy = event.clientY - dragState.lastY;
if (dragState.type === "point") {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
if (raycaster.ray.intersectPlane(dragPlane, planeHit)) {
const point = points[dragState.index];
point.x = THREE.MathUtils.clamp(planeHit.x, -4.6, 4.6);
point.y = THREE.MathUtils.clamp(planeHit.y, -3.5, 3.5);
updateGeometry();
}
return;
}
dragState.lastX = event.clientX;
dragState.lastY = event.clientY;
if (dragState.type === "orbit") {
const offset = camera.position.clone().sub(cameraTarget);
const spherical = new THREE.Spherical().setFromVector3(offset);
spherical.theta -= dx * 0.0055;
spherical.phi = THREE.MathUtils.clamp(
spherical.phi - dy * 0.0055,
0.22,
Math.PI - 0.22
);
camera.position
.copy(cameraTarget)
.add(new THREE.Vector3().setFromSpherical(spherical));
camera.lookAt(cameraTarget);
} else if (dragState.type === "pan") {
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
const distance = camera.position.distanceTo(cameraTarget);
const scale = distance * 0.00145;
const movement = right
.clone()
.multiplyScalar(-dx * scale)
.add(up.clone().multiplyScalar(dy * scale));
cameraTarget.add(movement);
camera.position.add(movement);
camera.lookAt(cameraTarget);
}
});
function endPointerDrag(event) {
if (!dragState || dragState.pointerId !== event.pointerId) return;
dragState = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointerDrag);
renderer.domElement.addEventListener("pointercancel", endPointerDrag);
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
function zoomBy(factor) {
const offset = camera.position.clone().sub(cameraTarget);
const distance = THREE.MathUtils.clamp(
offset.length() * factor,
4.8,
28
);
offset.setLength(distance);
camera.position.copy(cameraTarget).add(offset);
camera.lookAt(cameraTarget);
}
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
zoomBy(Math.exp(event.deltaY * 0.001));
},
{ passive: false }
);
$("zoomIn").addEventListener("click", () => zoomBy(0.84));
$("zoomOut").addEventListener("click", () => zoomBy(1.16));
window.addEventListener("keydown", (event) => {
if (["INPUT", "BUTTON"].includes(document.activeElement?.tagName)) return;
const step = event.shiftKey ? 0.5 : 0.1;
let changed = true;
switch (event.key) {
case "ArrowLeft":
points[selectedIndex].x -= step;
break;
case "ArrowRight":
points[selectedIndex].x += step;
break;
case "ArrowUp":
points[selectedIndex].y += step;
break;
case "ArrowDown":
points[selectedIndex].y -= step;
break;
default:
changed = false;
}
if (changed) {
event.preventDefault();
points[selectedIndex].x = THREE.MathUtils.clamp(points[selectedIndex].x, -4.6, 4.6);
points[selectedIndex].y = THREE.MathUtils.clamp(points[selectedIndex].y, -3.5, 3.5);
updateGeometry();
}
});
function resize() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
window.addEventListener("resize", resize);
resize();
syncVisibility();
selectPoint(0);
updateGeometry();
function animate(time) {
requestAnimationFrame(animate);
const pulse = 1 + Math.sin(time * 0.004) * 0.045;
selectionRings[selectedIndex].scale.setScalar(pulse);
updateLabelPositions();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```