Prompt specification
Build or customize the Three.js 3D scene "Vector projection tabletop" 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: Vector projection tabletop
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/vector-projection-tabletop-x1753
Scene Description Prompt:
Explore low-poly vector projection with two arrows, a perpendicular segment, and signed dot-product values. Make one HTML file using Three.js from cdnjs.
Working Three.js Starter (vector-projection-tabletop-x1753):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Signed Projection — Low-Poly Vector Lab</title>
<style>
:root {
--bg: #070b14;
--panel: rgba(13, 20, 34, 0.82);
--panel-border: rgba(154, 188, 222, 0.16);
--text: #edf5ff;
--muted: #8494aa;
--cyan: #58e6d1;
--orange: #ffb45b;
--purple: #c58bff;
--yellow: #ffe28a;
--red: #ff7188;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
body {
background:
radial-gradient(circle at 52% 44%, #122139 0%, #090f1c 42%, #050810 100%);
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
outline: none;
}
#scene:active {
cursor: grabbing;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
linear-gradient(90deg, rgba(3, 7, 14, 0.34), transparent 26%, transparent 74%, rgba(3, 7, 14, 0.34)),
linear-gradient(0deg, rgba(3, 7, 14, 0.42), transparent 25%, transparent 78%, rgba(3, 7, 14, 0.28));
}
.brand,
.controls,
.stats,
.hint {
position: fixed;
z-index: 5;
}
.brand {
top: 26px;
left: 28px;
width: 280px;
pointer-events: none;
}
.eyebrow {
margin-bottom: 10px;
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.brand h1 {
margin: 0;
font-size: clamp(34px, 4.6vw, 66px);
font-weight: 760;
line-height: 0.87;
letter-spacing: -0.065em;
}
.brand h1 span {
color: var(--cyan);
}
.brand p {
width: 250px;
margin: 17px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.65;
}
.panel {
border: 1px solid var(--panel-border);
border-radius: 18px;
background: var(--panel);
box-shadow:
0 20px 60px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.035);
backdrop-filter: blur(18px) saturate(125%);
-webkit-backdrop-filter: blur(18px) saturate(125%);
}
.controls {
bottom: 26px;
left: 28px;
width: 330px;
padding: 18px;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
color: #d8e5f5;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.panel-heading span:last-child {
color: #62748c;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.08em;
}
.control {
display: block;
margin-top: 14px;
}
.control-line {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
color: #a9b8cb;
font-size: 11px;
}
.control-line output {
min-width: 64px;
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
text-align: right;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 10px;
appearance: none;
-webkit-appearance: none;
background: linear-gradient(90deg, #405069, #1c293c);
cursor: pointer;
outline: none;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #dceeff;
border-radius: 50%;
appearance: none;
-webkit-appearance: none;
background: var(--cyan);
box-shadow: 0 0 0 5px rgba(88, 230, 209, 0.09);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #dceeff;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 5px rgba(88, 230, 209, 0.09);
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 8px;
margin-top: 18px;
}
button {
min-height: 36px;
padding: 8px 9px;
border: 1px solid rgba(174, 200, 227, 0.15);
border-radius: 9px;
background: rgba(255, 255, 255, 0.045);
color: #c9d6e6;
font: inherit;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.03em;
cursor: pointer;
transition:
background 160ms ease,
border-color 160ms ease,
color 160ms ease,
transform 160ms ease;
}
button:hover {
border-color: rgba(88, 230, 209, 0.4);
background: rgba(88, 230, 209, 0.08);
color: white;
transform: translateY(-1px);
}
button.active {
border-color: rgba(88, 230, 209, 0.55);
background: rgba(88, 230, 209, 0.13);
color: var(--cyan);
}
.formula {
margin-top: 15px;
padding-top: 13px;
border-top: 1px solid rgba(255, 255, 255, 0.07);
color: #73859d;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.55;
}
.formula b {
color: var(--yellow);
font-weight: 500;
}
.stats {
top: 26px;
right: 28px;
width: 284px;
padding: 18px;
}
.product-list {
display: grid;
gap: 9px;
}
.product {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 11px;
border: 1px solid rgba(255, 255, 255, 0.055);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.product span {
color: #8394aa;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
}
.product strong {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
font-weight: 650;
color: var(--text);
}
.product strong[data-sign="positive"] {
color: var(--cyan);
}
.product strong[data-sign="negative"] {
color: var(--red);
}
.product strong[data-sign="zero"] {
color: #8998aa;
}
.legend {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px 12px;
margin-top: 16px;
padding-top: 14px;
border-top: 1px solid rgba(255, 255, 255, 0.07);
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
color: #7f90a7;
font-size: 10px;
}
.swatch {
width: 16px;
height: 4px;
border-radius: 4px;
}
.note {
margin: 14px 0 0;
color: #62738a;
font-size: 10px;
line-height: 1.55;
}
.world-label {
position: fixed;
z-index: 3;
display: flex;
align-items: center;
gap: 6px;
padding: 5px 8px;
border: 1px solid rgba(255, 255, 255, 0.11);
border-radius: 7px;
background: rgba(7, 12, 22, 0.76);
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.22);
color: #eaf4ff;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1;
white-space: nowrap;
pointer-events: none;
transform: translate(-50%, -50%);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
}
.world-label b {
font-size: 11px;
}
.world-label span {
color: #8293aa;
font-size: 9px;
}
.world-label.cyan {
border-color: rgba(88, 230, 209, 0.3);
color: var(--cyan);
}
.world-label.orange {
border-color: rgba(255, 180, 91, 0.3);
color: var(--orange);
}
.world-label.purple {
border-color: rgba(197, 139, 255, 0.32);
color: var(--purple);
}
.world-label.yellow {
border-color: rgba(255, 226, 138, 0.32);
color: var(--yellow);
}
.world-label.compact {
padding: 4px 7px;
border-radius: 50%;
}
.world-label.product-world {
flex-direction: column;
align-items: flex-start;
gap: 3px;
}
.world-label.product-world b[data-sign="positive"] {
color: var(--cyan);
}
.world-label.product-world b[data-sign="negative"] {
color: var(--red);
}
.world-label.product-world b[data-sign="zero"] {
color: #91a0b1;
}
.hint {
right: 28px;
bottom: 27px;
display: flex;
align-items: center;
gap: 9px;
color: #61738b;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.04em;
pointer-events: none;
}
.hint::before {
content: "";
width: 7px;
height: 7px;
border: 1px solid #64758c;
border-radius: 50%;
}
@media (max-width: 820px) {
.brand {
top: 14px;
left: 15px;
width: 190px;
}
.brand h1 {
font-size: 36px;
}
.brand p {
display: none;
}
.eyebrow {
margin-bottom: 7px;
font-size: 8px;
}
.stats {
top: 14px;
right: 14px;
width: 210px;
padding: 12px;
}
.stats .legend,
.stats .note {
display: none;
}
.panel-heading {
margin-bottom: 10px;
font-size: 9px;
}
.controls {
right: 14px;
bottom: 14px;
left: 14px;
width: auto;
max-height: 42vh;
padding: 14px;
overflow: auto;
}
.control {
margin-top: 10px;
}
.button-row {
margin-top: 12px;
}
.formula {
display: none;
}
.hint {
display: none;
}
.world-label {
padding: 4px 6px;
font-size: 9px;
}
}
@media (max-height: 620px) and (min-width: 821px) {
.brand p,
.stats .note {
display: none;
}
.controls {
bottom: 14px;
padding: 13px;
}
.control {
margin-top: 9px;
}
.button-row {
margin-top: 11px;
}
.formula {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive 3D vector projection visualization"></canvas>
<div class="vignette"></div>
<header class="brand">
<div class="eyebrow">Low-poly lab / signed geometry</div>
<h1>Signed<br /><span>Projection</span></h1>
<p>
Explore how a negative dot product reverses the projection while the
residual remains perpendicular to the reference vector.
</p>
</header>
<section class="stats panel" aria-live="polite">
<div class="panel-heading">
<span>Signed products</span>
<span>live geometry</span>
</div>
<div class="product-list">
<div class="product">
<span>A · B</span>
<strong id="dotAB">+10.26</strong>
</div>
<div class="product">
<span>A · R</span>
<strong id="dotAR" data-sign="zero">0</strong>
</div>
<div class="product">
<span>s = (A·B)/|A|²</span>
<strong id="projectionScalar">+0.410</strong>
</div>
<div class="product">
<span>angle θ</span>
<strong id="angleStat">+55.0°</strong>
</div>
</div>
<div class="legend">
<div class="legend-item">
<i class="swatch" style="background: var(--cyan)"></i>
Vector A
</div>
<div class="legend-item">
<i class="swatch" style="background: var(--orange)"></i>
Vector B
</div>
<div class="legend-item">
<i class="swatch" style="background: var(--yellow)"></i>
Projection
</div>
<div class="legend-item">
<i class="swatch" style="background: var(--purple)"></i>
Residual R
</div>
</div>
<p class="note">
R = B − proj<sub>A</sub>(B). The signed scalar s determines whether the
projection lies along or opposite A.
</p>
</section>
<section class="controls panel">
<div class="panel-heading">
<span>Vector controls</span>
<span>drag canvas to orbit</span>
</div>
<label class="control">
<span class="control-line">
<span>Magnitude |A|</span>
<output id="lengthAOutput">5.0</output>
</span>
<input id="lengthA" type="range" min="1" max="7" step="0.1" value="5" />
</label>
<label class="control">
<span class="control-line">
<span>Magnitude |B|</span>
<output id="lengthBOutput">4.0</output>
</span>
<input id="lengthB" type="range" min="1" max="7" step="0.1" value="4" />
</label>
<label class="control">
<span class="control-line">
<span>Signed angle θ</span>
<output id="angleOutput">+55.0°</output>
</span>
<input id="angle" type="range" min="-170" max="170" step="0.5" value="55" />
</label>
<div class="button-row">
<button id="animateButton" type="button">Animate</button>
<button id="flipButton" type="button">Flip B</button>
<button id="resetButton" type="button">Reset</button>
</div>
<div class="formula">
<b>P = ((A · B) / |A|²) A</b><br />
R = B − P / A · R = 0
</div>
</section>
<div id="labels" aria-hidden="true">
<div id="labelO" class="world-label compact">O</div>
<div id="labelA" class="world-label cyan">
<b>A</b><span id="labelALength">|A| = 5.0</span>
</div>
<div id="labelB" class="world-label orange">
<b>B</b><span id="labelBLength">|B| = 4.0</span>
</div>
<div id="labelP" class="world-label yellow">
<b>P</b><span>proj<sub>A</sub>(B)</span>
</div>
<div id="labelR" class="world-label purple">
<b>R</b><span>B − P</span>
</div>
<div id="labelDot" class="world-label product-world">
<span>A · B</span>
<b id="labelDotValue" data-sign="positive">+10.26</b>
</div>
<div id="labelZero" class="world-label product-world">
<span>A · R</span>
<b id="labelZeroValue" data-sign="zero">0</b>
</div>
<div id="labelAngle" class="world-label yellow">+55.0°</div>
</div>
<div class="hint">drag to orbit · wheel to zoom · double-click to reset view</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const canvas = $("scene");
// ---------------------------------------------------------------------
// Renderer, scene, and camera
// ---------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0x070b14, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const hemisphere = new THREE.HemisphereLight(0xa9ddff, 0x15101f, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(-4, 8, 10);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0xff86c8, 1.8);
rimLight.position.set(8, -3, 7);
scene.add(rimLight);
const coolRim = new THREE.DirectionalLight(0x58e6d1, 1.1);
coolRim.position.set(-8, -5, 2);
scene.add(coolRim);
const cameraState = {
radius: 17,
polar: 1.48,
azimuth: 0.08,
target: new THREE.Vector3(1.0, 0.15, 0)
};
const cameraHome = {
radius: 17,
polar: 1.48,
azimuth: 0.08
};
function updateCamera() {
const aspect = window.innerWidth / window.innerHeight;
const responsiveScale = Math.max(1, 0.92 / aspect);
const radius = cameraState.radius * responsiveScale;
const sinPolar = Math.sin(cameraState.polar);
const cosPolar = Math.cos(cameraState.polar);
camera.position.set(
cameraState.target.x + radius * sinPolar * Math.sin(cameraState.azimuth),
cameraState.target.y + radius * cosPolar,
cameraState.target.z + radius * sinPolar * Math.cos(cameraState.azimuth)
);
camera.lookAt(cameraState.target);
}
// ---------------------------------------------------------------------
// Low-poly vector construction
// ---------------------------------------------------------------------
const ORIGIN = new THREE.Vector3(0, 0, 0);
const Y_AXIS = new THREE.Vector3(0, 1, 0);
function lowPolyMaterial(color, emissiveIntensity = 0.08) {
return new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity,
roughness: 0.58,
metalness: 0.12,
flatShading: true
});
}
function createArrow(color) {
const group = new THREE.Group();
const shaftGeometry = new THREE.CylinderGeometry(1, 1, 1, 6, 1, false);
const headGeometry = new THREE.ConeGeometry(1, 1, 6, 1, false);
const shaft = new THREE.Mesh(shaftGeometry, lowPolyMaterial(color));
const head = new THREE.Mesh(headGeometry, lowPolyMaterial(color, 0.12));
group.add(shaft, head);
group.userData.shaft = shaft;
group.userData.head = head;
return group;
}
function updateArrow(arrow, start, end, radius = 0.075) {
const direction = end.clone().sub(start);
const length = direction.length();
if (length < 0.0001) {
arrow.visible = false;
return;
}
arrow.visible = true;
direction.normalize();
const headLength = Math.min(0.72, length * 0.22);
const shaftLength = Math.max(0.001, length - headLength);
arrow.position.copy(start);
arrow.quaternion.setFromUnitVectors(Y_AXIS, direction);
arrow.userData.shaft.scale.set(radius, shaftLength, radius);
arrow.userData.shaft.position.set(0, shaftLength / 2, 0);
arrow.userData.head.scale.set(radius * 2.8, headLength, radius * 2.8);
arrow.userData.head.position.set(0, shaftLength + headLength / 2, 0);
}
function createSegment(color, radius = 0.055) {
const geometry = new THREE.CylinderGeometry(1, 1, 1, 6, 1, false);
const mesh = new THREE.Mesh(geometry, lowPolyMaterial(color, 0.1));
mesh.userData.radius = radius;
return mesh;
}
function updateSegment(mesh, start, end) {
const direction = end.clone().sub(start);
const length = direction.length();
if (length < 0.0001) {
mesh.visible = false;
return;
}
direction.normalize();
mesh.visible = true;
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(Y_AXIS, direction);
mesh.scale.set(mesh.userData.radius, length, mesh.userData.radius);
}
const arrowA = createArrow(0x58e6d1);
const arrowB = createArrow(0xffb45b);
const residualSegment = createSegment(0xc58bff, 0.052);
scene.add(arrowA, arrowB, residualSegment);
// Dashed guide from the origin to the projection foot.
const projectionPositions = new Float32Array(6);
const projectionGeometry = new THREE.BufferGeometry();
projectionGeometry.setAttribute(
"position",
new THREE.BufferAttribute(projectionPositions, 3)
);
const projectionLine = new THREE.Line(
projectionGeometry,
new THREE.LineDashedMaterial({
color: 0xffe28a,
dashSize: 0.16,
gapSize: 0.11,
transparent: true,
opacity: 0.8
})
);
projectionLine.frustumCulled = false;
scene.add(projectionLine);
// Angle arc.
const ARC_SEGMENTS = 48;
const anglePositions = new Float32Array((ARC_SEGMENTS + 1) * 3);
const angleGeometry = new THREE.BufferGeometry();
angleGeometry.setAttribute(
"position",
new THREE.BufferAttribute(anglePositions, 3)
);
const angleArc = new THREE.Line(
angleGeometry,
new THREE.LineBasicMaterial({
color: 0xffe28a,
transparent: true,
opacity: 0.55
})
);
angleArc.frustumCulled = false;
scene.add(angleArc);
// Right-angle marker around the projection foot.
const markerPositions = new Float32Array(15);
const markerGeometry = new THREE.BufferGeometry();
markerGeometry.setAttribute(
"position",
new THREE.BufferAttribute(markerPositions, 3)
);
const rightAngleMarker = new THREE.Line(
markerGeometry,
new THREE.LineBasicMaterial({
color: 0xc58bff,
transparent: true,
opacity: 0.85
})
);
rightAngleMarker.frustumCulled = false;
scene.add(rightAngleMarker);
// Low-poly origin and projection markers.
const originMarker = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.145, 0),
lowPolyMaterial(0xf4f8ff, 0.13)
);
scene.add(originMarker);
const projectionMarker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.115, 0),
lowPolyMaterial(0xffe28a, 0.15)
);
scene.add(projectionMarker);
// ---------------------------------------------------------------------
// Background grid and low-poly decorations
// ---------------------------------------------------------------------
const grid = new THREE.Group();
grid.position.z = -1.05;
scene.add(grid);
const minorGridMaterial = new THREE.LineBasicMaterial({
color: 0x31445d,
transparent: true,
opacity: 0.16
});
const majorGridMaterial = new THREE.LineBasicMaterial({
color: 0x4b6686,
transparent: true,
opacity: 0.23
});
function addGridLine(points, material) {
const geometry = new THREE.BufferGeometry().setFromPoints(points);
grid.add(new THREE.Line(geometry, material));
}
for (let x = -11; x <= 11; x += 1) {
addGridLine(
[
new THREE.Vector3(x, -7, 0),
new THREE.Vector3(x, 7, 0)
],
x % 5 === 0 ? majorGridMaterial : minorGridMaterial
);
}
for (let y = -7; y <= 7; y += 1) {
addGridLine(
[
new THREE.Vector3(-11, y, 0),
new THREE.Vector3(11, y, 0)
],
y % 5 === 0 ? majorGridMaterial : minorGridMaterial
);
}
const axisLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-10, 0, 0.02),
new THREE.Vector3(10, 0, 0.02)
]),
new THREE.LineBasicMaterial({
color: 0x7290b0,
transparent: true,
opacity: 0.3
})
);
grid.add(axisLine);
const decorations = [
{ p: [-8.2, -5.1, -0.65], s: 0.7, c: 0x17283d },
{ p: [7.9, 5.0, -0.7], s: 0.82, c: 0x211a35 },
{ p: [-7.4, 5.4, -0.8], s: 0.38, c: 0x153036 },
{ p: [8.8, -4.7, -0.75], s: 0.48, c: 0x302118 }
];
for (const decoration of decorations) {
const mesh = new THREE.Mesh(
new THREE.IcosahedronGeometry(decoration.s, 0),
new THREE.MeshStandardMaterial({
color: decoration.c,
roughness: 1,
flatShading: true
})
);
mesh.position.set(...decoration.p);
mesh.rotation.set(0.3, 0.6, 0.1);
scene.add(mesh);
}
// ---------------------------------------------------------------------
// State and signed values
// ---------------------------------------------------------------------
const params = {
lengthA: 5,
lengthB: 4,
angle: 55
};
let animating = false;
let animationStart = 0;
let animationPhase = 0;
function signedText(value, digits = 2) {
if (Math.abs(value) < 0.5 * Math.pow(10, -digits)) {
return "0";
}
const sign = value > 0 ? "+" : "−";
return `${sign}${Math.abs(value).toFixed(digits)}`;
}
function signedAngle(value) {
if (Math.abs(value) < 0.05) {
return "0.0°";
}
return `${value > 0 ? "+" : "−"}${Math.abs(value).toFixed(1)}°`;
}
function setSignedValue(element, value, digits = 2) {
element.textContent = signedText(value, digits);
if (Math.abs(value) < 0.5 * Math.pow(10, -digits)) {
element.dataset.sign = "zero";
} else {
element.dataset.sign = value > 0 ? "positive" : "negative";
}
}
function setAnimation(active) {
animating = active;
$("animateButton").classList.toggle("active", active);
$("animateButton").textContent = active ? "Pause" : "Animate";
if (active) {
animationStart = performance.now();
animationPhase = Math.asin(
THREE.MathUtils.clamp(params.angle / 78, -1, 1)
);
}
}
function syncControls() {
$("lengthA").value = params.lengthA;
$("lengthB").value = params.lengthB;
$("angle").value = params.angle;
$("lengthAOutput").textContent = params.lengthA.toFixed(1);
$("lengthBOutput").textContent = params.lengthB.toFixed(1);
$("angleOutput").textContent = signedAngle(params.angle);
}
$("lengthA").addEventListener("input", (event) => {
params.lengthA = Number(event.target.value);
$("lengthAOutput").textContent = params.lengthA.toFixed(1);
});
$("lengthB").addEventListener("input", (event) => {
params.lengthB = Number(event.target.value);
$("lengthBOutput").textContent = params.lengthB.toFixed(1);
});
$("angle").addEventListener("input", (event) => {
setAnimation(false);
params.angle = Number(event.target.value);
$("angleOutput").textContent = signedAngle(params.angle);
});
$("animateButton").addEventListener("click", () => {
setAnimation(!animating);
});
$("flipButton").addEventListener("click", () => {
setAnimation(false);
params.angle = Math.abs(params.angle) < 0.5 ? -55 : -params.angle;
syncControls();
});
$("resetButton").addEventListener("click", () => {
setAnimation(false);
params.lengthA = 5;
params.lengthB = 4;
params.angle = 55;
syncControls();
});
// ---------------------------------------------------------------------
// Directly implemented camera controls
// ---------------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) {
return;
}
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
cameraState.azimuth -= deltaX * 0.006;
cameraState.polar = THREE.MathUtils.clamp(
cameraState.polar + deltaY * 0.005,
0.25,
Math.PI - 0.25
);
pointerX = event.clientX;
pointerY = event.clientY;
});
function endDrag(event) {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
9,
34
);
},
{ passive: false }
);
function resetCamera() {
cameraState.radius = cameraHome.radius;
cameraState.polar = cameraHome.polar;
cameraState.azimuth = cameraHome.azimuth;
cameraState.target.set(1.0, 0.15, 0);
}
canvas.addEventListener("dblclick", resetCamera);
// ---------------------------------------------------------------------
// Label projection without CSS2DRenderer or any addons
// ---------------------------------------------------------------------
const projectedPoint = new THREE.Vector3();
function placeLabel(element, worldPoint, offsetX = 0, offsetY = 0) {
projectedPoint.copy(worldPoint).project(camera);
const visible =
projectedPoint.z > -1 &&
projectedPoint.z < 1 &&
Math.abs(projectedPoint.x) < 1.25 &&
Math.abs(projectedPoint.y) < 1.25;
element.style.display = visible ? "flex" : "none";
if (!visible) {
return;
}
const x = (projectedPoint.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projectedPoint.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${x + offsetX}px`;
element.style.top = `${y + offsetY}px`;
}
// ---------------------------------------------------------------------
// Geometry update
// ---------------------------------------------------------------------
const vectorA = new THREE.Vector3();
const vectorB = new THREE.Vector3();
const projection = new THREE.Vector3();
const residual = new THREE.Vector3();
const residualMidpoint = new THREE.Vector3();
const angleLabelPoint = new THREE.Vector3();
function updateGeometry() {
const radians = THREE.MathUtils.degToRad(params.angle);
vectorA.set(params.lengthA, 0, 0);
vectorB.set(
params.lengthB * Math.cos(radians),
params.lengthB * Math.sin(radians),
0
);
const dotAB = vectorA.dot(vectorB);
const squaredLengthA = vectorA.lengthSq();
const scalar = dotAB / squaredLengthA;
projection.copy(vectorA).multiplyScalar(scalar);
residual.copy(vectorB).sub(projection);
residualMidpoint.copy(projection).add(residual).multiplyScalar(0.5);
const dotAR = vectorA.dot(residual);
updateArrow(arrowA, ORIGIN, vectorA, 0.078);
updateArrow(arrowB, ORIGIN, vectorB, 0.078);
updateSegment(residualSegment, projection, vectorB);
projectionMarker.position.copy(projection);
// Update the dashed origin-to-projection guide.
projectionPositions[0] = ORIGIN.x;
projectionPositions[1] = ORIGIN.y;
projectionPositions[2] = 0.13;
projectionPositions[3] = projection.x;
projectionPositions[4] = projection.y;
projectionPositions[5] = 0.13;
projectionGeometry.attributes.position.needsUpdate = true;
projectionLine.computeLineDistances();
projectionLine.visible = projection.length() > 0.015;
// Update the signed angle arc.
const arcRadius = 1.1;
for (let i = 0; i <= ARC_SEGMENTS; i++) {
const t = radians * (i / ARC_SEGMENTS);
const index = i * 3;
anglePositions[index] = Math.cos(t) * arcRadius;
anglePositions[index + 1] = Math.sin(t) * arcRadius;
anglePositions[index + 2] = 0.12;
}
angleGeometry.attributes.position.needsUpdate = true;
angleArc.visible = Math.abs(params.angle) > 0.5;
// Update the right-angle marker.
const residualSign = Math.sign(residual.y) || 1;
const markerSize = THREE.MathUtils.clamp(
Math.abs(residual.y) * 0.38,
0.12,
0.28
);
const markerPoints = [
[projection.x, projection.y],
[projection.x + markerSize, projection.y],
[projection.x + markerSize, projection.y + markerSize * residualSign],
[projection.x, projection.y + markerSize * residualSign],
[projection.x, projection.y]
];
markerPoints.forEach((point, index) => {
markerPositions[index * 3] = point[0];
markerPositions[index * 3 + 1] = point[1];
markerPositions[index * 3 + 2] = 0.14;
});
markerGeometry.attributes.position.needsUpdate = true;
rightAngleMarker.visible = residual.length() > 0.04;
// Numeric readouts.
setSignedValue($("dotAB"), dotAB, 2);
setSignedValue($("dotAR"), dotAR, 2);
setSignedValue($("projectionScalar"), scalar, 3);
$("angleStat").textContent = signedAngle(params.angle);
$("labelALength").textContent = `|A| = ${params.lengthA.toFixed(1)}`;
$("labelBLength").textContent = `|B| = ${params.lengthB.toFixed(1)}`;
$("labelAngle").textContent = signedAngle(params.angle);
setSignedValue($("labelDotValue"), dotAB, 2);
setSignedValue($("labelZeroValue"), dotAR, 2);
// Position all labels after the camera has been updated.
placeLabel($("labelO"), ORIGIN, 0, 18);
placeLabel($("labelA"), vectorA, 0, -22);
placeLabel($("labelB"), vectorB, 12, -23);
placeLabel($("labelP"), projection, 0, 25);
placeLabel($("labelR"), residualMidpoint, 22, 0);
const dotLabelPoint = ORIGIN.clone().add(new THREE.Vector3(-0.9, -0.62, 0.2));
const zeroLabelPoint = ORIGIN.clone().add(new THREE.Vector3(0.95, -0.62, 0.2));
placeLabel($("labelDot"), dotLabelPoint);
placeLabel($("labelZero"), zeroLabelPoint);
angleLabelPoint.set(
Math.cos(radians) * 1.48,
Math.sin(radians) * 1.48,
0.15
);
placeLabel($("labelAngle"), angleLabelPoint);
}
// ---------------------------------------------------------------------
// Resize and render loop
// ---------------------------------------------------------------------
function onResize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
updateCamera();
}
window.addEventListener("resize", onResize);
function animate(now) {
requestAnimationFrame(animate);
if (animating) {
const elapsed = (now - animationStart) / 1000;
params.angle = 78 * Math.sin(animationPhase + elapsed * 0.55);
$("angle").value = params.angle.toFixed(1);
$("angleOutput").textContent = signedAngle(params.angle);
}
updateCamera();
updateGeometry();
originMarker.rotation.x += 0.006;
originMarker.rotation.y += 0.009;
projectionMarker.rotation.x -= 0.012;
projectionMarker.rotation.z += 0.008;
renderer.render(scene, camera);
}
syncControls();
onResize();
requestAnimationFrame(animate);
</script>
</body>
</html>
```