Prompt specification
Build or customize the Three.js 3D scene "Magnified knit-loop structure" 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: Magnified knit-loop structure
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/magnified-knit-loop-structure-x0597
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts knitted fabric loops. Build a small patch of thick yarn loops with neighboring rows interlinked; color one continuous yarn path so its route can be traced across the fabric. Voxel style.
Working Three.js Starter (magnified-knit-loop-structure-x0597):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Loop / Trace — Voxel Knit Study</title>
<style>
:root {
--ink: #28251f;
--muted: #746f64;
--paper: #ebe6dc;
--accent: #ff584d;
--accent-light: #ffcf67;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--paper);
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#app {
position: relative;
width: 100%;
height: 100%;
isolation: isolate;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
#app::after {
content: "";
position: absolute;
inset: 0;
z-index: 2;
pointer-events: none;
background:
radial-gradient(
circle at 50% 45%,
transparent 42%,
rgba(72, 61, 45, 0.07) 100%
);
}
.panel {
position: absolute;
z-index: 3;
pointer-events: none;
}
.intro {
top: 30px;
left: 34px;
width: min(340px, calc(100vw - 68px));
}
.eyebrow {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 12px;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.22em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 24px;
height: 4px;
border-radius: 99px;
background: var(--accent);
box-shadow: 0 0 0 4px rgba(255, 88, 77, 0.12);
}
h1 {
margin: 0;
font-size: clamp(36px, 5vw, 64px);
font-weight: 800;
line-height: 0.9;
letter-spacing: -0.065em;
text-transform: uppercase;
}
h1 span {
color: var(--accent);
}
.intro p {
max-width: 310px;
margin: 18px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.65;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 18px;
margin-top: 20px;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.legend-item {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 13px;
height: 13px;
border-radius: 3px;
box-shadow: inset 0 0 0 1px rgba(45, 37, 26, 0.12);
}
.swatch.path {
background: var(--accent);
}
.swatch.weave {
background: #d8c7aa;
}
.controls {
right: 26px;
bottom: 24px;
display: flex;
align-items: center;
gap: 8px;
pointer-events: auto;
}
button {
appearance: none;
border: 1px solid rgba(55, 48, 38, 0.15);
border-radius: 9px;
padding: 10px 13px;
background: rgba(250, 247, 240, 0.76);
color: var(--ink);
font: inherit;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
backdrop-filter: blur(10px);
transition:
transform 150ms ease,
background 150ms ease,
border-color 150ms ease;
}
button:hover {
transform: translateY(-1px);
border-color: rgba(255, 88, 77, 0.42);
background: rgba(255, 252, 246, 0.94);
}
button:active {
transform: translateY(0);
}
button.primary {
border-color: transparent;
background: var(--accent);
color: white;
}
.hint {
right: 28px;
top: 27px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.stats {
left: 34px;
bottom: 27px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
@media (max-width: 700px) {
.intro {
top: 22px;
left: 22px;
}
.intro p {
max-width: 250px;
font-size: 12px;
}
.legend {
gap: 12px;
}
.hint,
.stats {
display: none;
}
.controls {
right: 16px;
bottom: 16px;
}
}
</style>
</head>
<body>
<main id="app">
<canvas id="scene" aria-label="Interactive voxel knitted fabric scene"></canvas>
<section class="panel intro">
<div class="eyebrow">Voxel textile study · 04</div>
<h1>Loop<br /><span>/ Trace</span></h1>
<p>
A small field of chunky knitted loops. The coral yarn is one continuous
path, moving across each row and dropping through the edge loops.
</p>
<div class="legend" aria-label="Scene legend">
<div class="legend-item">
<span class="swatch path"></span>
Continuous yarn
</div>
<div class="legend-item">
<span class="swatch weave"></span>
Interlinked loops
</div>
</div>
</section>
<div class="panel hint">Drag to orbit · Scroll to zoom</div>
<div class="panel stats">28 loops · 4 rows · 1 traced path</div>
<div class="panel controls">
<button id="pause" class="primary" type="button">Pause trace</button>
<button id="reset" type="button">Reset view</button>
</div>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
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;
const scene = new THREE.Scene();
scene.background = new THREE.Color("#ebe6dc");
scene.fog = new THREE.Fog("#ebe6dc", 15, 27);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 50);
const cameraTarget = new THREE.Vector3(0, 0.02, 0);
const hemisphere = new THREE.HemisphereLight(
"#fffdf6",
"#81715d",
1.55
);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight("#fff4df", 3.3);
keyLight.position.set(-4.5, 7.5, 8.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 22;
keyLight.shadow.bias = -0.00035;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight("#b8d9e8", 1.15);
rimLight.position.set(6, -2, 5);
scene.add(rimLight);
const fabric = new THREE.Group();
fabric.rotation.y = -0.055;
fabric.rotation.x = -0.025;
scene.add(fabric);
// A quiet backing card gives the floating textile a clear silhouette.
const cardGeometry = new THREE.BoxGeometry(6.35, 5.42, 0.16);
const cardMaterial = new THREE.MeshStandardMaterial({
color: "#ded8cc",
roughness: 0.96,
metalness: 0
});
const card = new THREE.Mesh(cardGeometry, cardMaterial);
card.position.z = -0.86;
card.receiveShadow = true;
card.castShadow = true;
scene.add(card);
const cardEdge = new THREE.LineSegments(
new THREE.EdgesGeometry(cardGeometry),
new THREE.LineBasicMaterial({
color: "#b9b1a2",
transparent: true,
opacity: 0.38
})
);
cardEdge.position.copy(card.position);
scene.add(cardEdge);
// -------------------------------------------------------------------------
// Geometry helpers
// -------------------------------------------------------------------------
const ROWS = 4;
const COLS = 7;
const STITCH_SPACING = 0.82;
const ROW_SPACING = 1.05;
const HALF_LOOP_HEIGHT = 0.6;
const LEG_OFFSET = 0.22;
const CENTER_X = (COLS - 1) * STITCH_SPACING * 0.5;
const ROW_Y = Array.from(
{ length: ROWS },
(_, i) => (ROWS - 1) * 0.5 * ROW_SPACING - i * ROW_SPACING
);
const LEFT_CENTER = -CENTER_X;
const RIGHT_CENTER = CENTER_X;
const Y_AXIS = new THREE.Vector3(0, 1, 0);
const dummy = new THREE.Object3D();
function cubicPoint(p0, p1, p2, p3, t, target = new THREE.Vector3()) {
const u = 1 - t;
const u2 = u * u;
const u3 = u2 * u;
const t2 = t * t;
const t3 = t2 * t;
return target.set(
u3 * p0.x +
3 * u2 * t * p1.x +
3 * u * t2 * p2.x +
t3 * p3.x,
u3 * p0.y +
3 * u2 * t * p1.y +
3 * u * t2 * p2.y +
t3 * p3.y,
u3 * p0.z +
3 * u2 * t * p1.z +
3 * u * t2 * p2.z +
t3 * p3.z
);
}
function appendCubic(points, p0, p1, p2, p3, segments = 28) {
for (let i = 0; i <= segments; i++) {
if (i === 0 && points.length > 0) continue;
points.push(cubicPoint(p0, p1, p2, p3, i / segments));
}
}
function appendLine(points, start, end, segments = 20) {
for (let i = 0; i <= segments; i++) {
if (i === 0 && points.length > 0) continue;
const t = i / segments;
points.push(
new THREE.Vector3(
THREE.MathUtils.lerp(start.x, end.x, t),
THREE.MathUtils.lerp(start.y, end.y, t),
THREE.MathUtils.lerp(start.z, end.z, t)
)
);
}
}
function stitchCurves(centerX, rowY) {
const topY = rowY + HALF_LOOP_HEIGHT;
const bottomY = rowY - HALF_LOOP_HEIGHT;
const leftTop = new THREE.Vector3(
centerX - LEG_OFFSET,
topY,
-0.11
);
const leftControlA = new THREE.Vector3(
centerX - 0.3,
rowY + 0.12,
0.09
);
const leftControlB = new THREE.Vector3(
centerX - 0.25,
rowY - 0.43,
0.27
);
const bottom = new THREE.Vector3(centerX, bottomY, 0.27);
const rightControlA = new THREE.Vector3(
centerX + 0.25,
rowY - 0.43,
0.27
);
const rightControlB = new THREE.Vector3(
centerX + 0.3,
rowY + 0.12,
0.09
);
const rightTop = new THREE.Vector3(
centerX + LEG_OFFSET,
topY,
-0.11
);
const leftHalf = [];
appendCubic(
leftHalf,
leftTop,
leftControlA,
leftControlB,
bottom,
32
);
const rightHalf = [];
appendCubic(
rightHalf,
bottom,
rightControlA,
rightControlB,
rightTop,
32
);
return {
all: [...leftHalf, ...rightHalf.slice(1)],
leftHalf,
rightHalf,
leftTop,
rightTop,
leftControlA,
leftControlB,
rightControlA,
rightControlB,
bottom
};
}
function resamplePolyline(points, spacing) {
const cumulative = [0];
for (let i = 1; i < points.length; i++) {
cumulative.push(
cumulative[i - 1] + points[i].distanceTo(points[i - 1])
);
}
const totalLength = cumulative[cumulative.length - 1];
const count = Math.max(2, Math.ceil(totalLength / spacing) + 1);
const samples = [];
let segment = 1;
for (let i = 0; i < count; i++) {
const distance = Math.min(
totalLength,
(i / (count - 1)) * totalLength
);
while (
segment < cumulative.length - 1 &&
cumulative[segment] < distance
) {
segment++;
}
const startDistance = cumulative[segment - 1];
const segmentLength = cumulative[segment] - startDistance;
const localT =
segmentLength === 0
? 0
: (distance - startDistance) / segmentLength;
const point = points[segment - 1].clone().lerp(
points[segment],
localT
);
const tangent = points[segment]
.clone()
.sub(points[segment - 1])
.normalize();
samples.push({ point, tangent, distance });
}
return { samples, totalLength };
}
function makeInstances(
points,
thickness,
colorA,
colorB,
twistOffset = 0
) {
const { samples } = resamplePolyline(points, 0.062);
const instances = [];
const alignQuaternion = new THREE.Quaternion();
const twistQuaternion = new THREE.Quaternion();
for (const sample of samples) {
alignQuaternion.setFromUnitVectors(Y_AXIS, sample.tangent);
twistQuaternion.setFromAxisAngle(
Y_AXIS,
sample.distance * 5.1 + twistOffset
);
const quaternion = alignQuaternion
.clone()
.multiply(twistQuaternion);
const stripe = 0.5 + 0.5 * Math.sin(sample.distance * 15.5);
const variation = THREE.MathUtils.clamp(
stripe * 0.28 + (sample.distance % 1) * 0.07,
0,
0.38
);
instances.push({
position: sample.point,
quaternion,
scale: new THREE.Vector3(
thickness,
thickness * 1.02,
thickness
),
color: colorA.clone().lerp(colorB, variation)
});
}
return instances;
}
function createYarnMesh(instances, material) {
const geometry = new THREE.BoxGeometry(1, 1, 1);
const mesh = new THREE.InstancedMesh(
geometry,
material,
instances.length
);
instances.forEach((instance, index) => {
dummy.position.copy(instance.position);
dummy.quaternion.copy(instance.quaternion);
dummy.scale.copy(instance.scale);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
mesh.setColorAt(index, instance.color);
});
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.computeBoundingSphere();
return mesh;
}
// -------------------------------------------------------------------------
// Build the neutral knitted fabric
// -------------------------------------------------------------------------
const baseInstances = [];
const rowPalettes = [
["#cdb894", "#e3d2b7"],
["#d4c09d", "#eadbc3"],
["#c9b38f", "#dfcdb0"],
["#d7c3a0", "#ecddc4"]
];
ROW_Y.forEach((rowY, rowIndex) => {
const rowPoints = [];
for (let column = 0; column < COLS; column++) {
const centerX = -CENTER_X + column * STITCH_SPACING;
const stitch = stitchCurves(centerX, rowY);
for (const point of stitch.all) {
if (rowPoints.length === 0) {
rowPoints.push(point.clone());
} else {
const previous = rowPoints[rowPoints.length - 1];
if (previous.distanceToSquared(point) > 0.000001) {
rowPoints.push(point.clone());
}
}
}
if (column < COLS - 1) {
const nextCenter =
-CENTER_X + (column + 1) * STITCH_SPACING;
appendLine(
rowPoints,
stitch.rightTop,
new THREE.Vector3(
nextCenter - LEG_OFFSET,
rowY + HALF_LOOP_HEIGHT,
-0.11
),
12
);
}
}
baseInstances.push(
...makeInstances(
rowPoints,
0.132,
new THREE.Color(rowPalettes[rowIndex][0]),
new THREE.Color(rowPalettes[rowIndex][1]),
rowIndex * 0.8
)
);
});
const baseMaterial = new THREE.MeshStandardMaterial({
color: "#ffffff",
roughness: 0.88,
metalness: 0
});
const baseMesh = createYarnMesh(baseInstances, baseMaterial);
fabric.add(baseMesh);
// -------------------------------------------------------------------------
// Build one continuous highlighted path across all four rows
// -------------------------------------------------------------------------
const heroPoints = [];
let previousHalfBottom = null;
for (let rowIndex = 0; rowIndex < ROWS; rowIndex++) {
const rowY = ROW_Y[rowIndex];
const topY = rowY + HALF_LOOP_HEIGHT;
const movingRight = rowIndex % 2 === 0;
const startCenter = movingRight ? LEFT_CENTER : RIGHT_CENTER;
const exitCenter = movingRight ? RIGHT_CENTER : LEFT_CENTER;
const exitInner = exitCenter - movingRight * LEG_OFFSET;
if (rowIndex === 0) {
appendCubic(
heroPoints,
new THREE.Vector3(-3.38, topY + 0.39, 0.13),
new THREE.Vector3(-3.15, topY + 0.28, 0.12),
new THREE.Vector3(-2.82, topY + 0.1, 0.08),
new THREE.Vector3(-2.52, topY, 0.04),
24
);
} else {
const transitionEnd = new THREE.Vector3(
startCenter,
topY,
0.04
);
appendCubic(
heroPoints,
previousHalfBottom,
new THREE.Vector3(
startCenter,
previousHalfBottom.y + 0.08,
0.31
),
new THREE.Vector3(
startCenter,
transitionEnd.y - 0.06,
0.12
),
transitionEnd,
24
);
}
appendLine(
heroPoints,
new THREE.Vector3(startCenter, topY, 0.04),
new THREE.Vector3(exitInner, topY, 0.04),
86
);
const exitStitch = stitchCurves(exitCenter, rowY);
if (movingRight) {
// Travel down the left half of the rightmost loop.
appendCubic(
heroPoints,
exitStitch.leftTop.clone().add(new THREE.Vector3(0, 0, 0.15)),
exitStitch.leftControlA.clone().add(new THREE.Vector3(0, 0, 0.15)),
exitStitch.leftControlB.clone().add(new THREE.Vector3(0, 0, 0.15)),
exitStitch.bottom.clone().add(new THREE.Vector3(0, 0, 0.15)),
34
);
} else {
// Travel down the right half of the leftmost loop.
appendCubic(
heroPoints,
exitStitch.rightTop.clone().add(new THREE.Vector3(0, 0, 0.15)),
exitStitch.rightControlB.clone().add(new THREE.Vector3(0, 0, 0.15)),
exitStitch.rightControlA.clone().add(new THREE.Vector3(0, 0, 0.15)),
exitStitch.bottom.clone().add(new THREE.Vector3(0, 0, 0.15)),
34
);
}
previousHalfBottom = exitStitch.bottom
.clone()
.add(new THREE.Vector3(0, 0, 0.15));
}
// Loose end below the final row.
appendCubic(
heroPoints,
previousHalfBottom,
new THREE.Vector3(
previousHalfBottom.x - 0.22,
previousHalfBottom.y - 0.12,
0.31
),
new THREE.Vector3(
previousHalfBottom.x - 0.54,
previousHalfBottom.y - 0.33,
0.15
),
new THREE.Vector3(
previousHalfBottom.x - 0.82,
previousHalfBottom.y - 0.49,
0.08
),
28
);
const heroInstances = makeInstances(
heroPoints,
0.15,
new THREE.Color("#f0443d"),
new THREE.Color("#ff8b65"),
0.7
);
const heroMaterial = new THREE.MeshStandardMaterial({
color: "#ffffff",
roughness: 0.68,
metalness: 0,
emissive: "#360806",
emissiveIntensity: 0.2
});
const heroMesh = createYarnMesh(heroInstances, heroMaterial);
fabric.add(heroMesh);
// -------------------------------------------------------------------------
// Arc-length path used by the moving tracer
// -------------------------------------------------------------------------
function makeArcPath(points) {
const cumulative = [0];
for (let i = 1; i < points.length; i++) {
cumulative.push(
cumulative[i - 1] + points[i].distanceTo(points[i - 1])
);
}
const length = cumulative[cumulative.length - 1];
function pointAtDistance(distance) {
const wrapped = THREE.MathUtils.euclideanModulo(distance, length);
let low = 0;
let high = cumulative.length - 1;
while (low < high) {
const middle = Math.floor((low + high) / 2);
if (cumulative[middle] < wrapped) low = middle + 1;
else high = middle;
}
const index = Math.max(1, low);
const segmentStart = cumulative[index - 1];
const segmentLength = cumulative[index] - segmentStart;
const t =
segmentLength === 0
? 0
: (wrapped - segmentStart) / segmentLength;
return points[index - 1].clone().lerp(points[index], t);
}
function tangentAtDistance(distance) {
const wrapped = THREE.MathUtils.euclideanModulo(distance, length);
let low = 0;
let high = cumulative.length - 1;
while (low < high) {
const middle = Math.floor((low + high) / 2);
if (cumulative[middle] < wrapped) low = middle + 1;
else high = middle;
}
const index = Math.max(1, low);
return points[index]
.clone()
.sub(points[index - 1])
.normalize();
}
return { length, pointAtDistance, tangentAtDistance };
}
const heroArcPath = makeArcPath(heroPoints);
const tracerGroup = new THREE.Group();
fabric.add(tracerGroup);
const tracerGeometry = new THREE.BoxGeometry(0.13, 0.13, 0.13);
const tracerMarkers = [];
for (let i = 0; i < 7; i++) {
const marker = new THREE.Mesh(
tracerGeometry,
new THREE.MeshStandardMaterial({
color: i === 0 ? "#ffe28b" : "#ff9a59",
emissive: i === 0 ? "#ff9d25" : "#ff4b27",
emissiveIntensity: i === 0 ? 1.25 : 0.65,
roughness: 0.32,
metalness: 0
})
);
marker.castShadow = true;
tracerGroup.add(marker);
tracerMarkers.push(marker);
}
const tracerLight = new THREE.PointLight("#ffad52", 0.7, 2.1, 2);
tracerGroup.add(tracerLight);
let traceProgress = 0.08;
let traceRunning = true;
function updateTracer() {
tracerMarkers.forEach((marker, index) => {
const distance =
(traceProgress - index * 0.075) * heroArcPath.length;
const position = heroArcPath.pointAtDistance(distance);
const tangent = heroArcPath.tangentAtDistance(distance);
marker.position.copy(position);
marker.quaternion.setFromUnitVectors(Y_AXIS, tangent);
const scale = index === 0 ? 1.25 : 0.86 - index * 0.07;
marker.scale.setScalar(Math.max(0.24, scale));
});
tracerLight.position.copy(tracerMarkers[0].position);
}
// -------------------------------------------------------------------------
// Direct camera controls — no external control modules
// -------------------------------------------------------------------------
const cameraState = {
theta: 0.18,
phi: 1.39,
radius: 8.4,
targetTheta: 0.18,
targetPhi: 1.39,
targetRadius: 8.4,
autoFit: true
};
const pointers = new Map();
let previousPinchDistance = 0;
function clampCamera() {
cameraState.targetTheta = THREE.MathUtils.clamp(
cameraState.targetTheta,
-1.05,
1.05
);
cameraState.targetPhi = THREE.MathUtils.clamp(
cameraState.targetPhi,
0.7,
2.08
);
cameraState.targetRadius = THREE.MathUtils.clamp(
cameraState.targetRadius,
5.2,
18
);
}
function updateCamera() {
const easing = 0.12;
cameraState.theta = THREE.MathUtils.lerp(
cameraState.theta,
cameraState.targetTheta,
easing
);
cameraState.phi = THREE.MathUtils.lerp(
cameraState.phi,
cameraState.targetPhi,
easing
);
cameraState.radius = THREE.MathUtils.lerp(
cameraState.radius,
cameraState.targetRadius,
easing
);
const spherical = new THREE.Spherical(
cameraState.radius,
cameraState.phi,
cameraState.theta
);
camera.position.setFromSpherical(spherical).add(cameraTarget);
camera.lookAt(cameraTarget);
}
function getPinchDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 2) {
previousPinchDistance = getPinchDistance();
}
});
canvas.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
const previous = pointers.get(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
cameraState.targetTheta -=
(event.clientX - previous.x) * 0.006;
cameraState.targetPhi -=
(event.clientY - previous.y) * 0.005;
} else if (pointers.size === 2) {
const distance = getPinchDistance();
if (previousPinchDistance > 0 && distance > 0) {
cameraState.targetRadius *=
previousPinchDistance / distance;
cameraState.autoFit = false;
}
previousPinchDistance = distance;
}
clampCamera();
});
function endPointer(event) {
pointers.delete(event.pointerId);
previousPinchDistance =
pointers.size === 2 ? getPinchDistance() : 0;
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.targetRadius *= Math.exp(event.deltaY * 0.001);
cameraState.autoFit = false;
clampCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetView);
window.addEventListener("keydown", (event) => {
const key = event.key.toLowerCase();
if (key === "arrowleft") cameraState.targetTheta -= 0.08;
else if (key === "arrowright") cameraState.targetTheta += 0.08;
else if (key === "arrowup") cameraState.targetPhi -= 0.06;
else if (key === "arrowdown") cameraState.targetPhi += 0.06;
else return;
event.preventDefault();
clampCamera();
});
function fitCamera() {
const verticalFov = THREE.MathUtils.degToRad(camera.fov);
const horizontalHalfExtent = 3.5;
const fitForWidth =
horizontalHalfExtent /
Math.tan(verticalFov * 0.5) *
camera.aspect;
const fitForHeight = 2.95 / Math.tan(verticalFov * 0.5);
const fitDistance = Math.max(fitForWidth, fitForHeight, 8.4);
if (cameraState.autoFit) {
cameraState.radius = fitDistance;
cameraState.targetRadius = fitDistance;
}
}
function resetView() {
cameraState.targetTheta = 0.18;
cameraState.targetPhi = 1.39;
cameraState.autoFit = true;
fitCamera();
clampCamera();
}
// -------------------------------------------------------------------------
// UI and resize
// -------------------------------------------------------------------------
const pauseButton = document.querySelector("#pause");
const resetButton = document.querySelector("#reset");
pauseButton.addEventListener("click", () => {
traceRunning = !traceRunning;
pauseButton.textContent = traceRunning ? "Pause trace" : "Resume trace";
pauseButton.setAttribute("aria-pressed", String(!traceRunning));
});
resetButton.addEventListener("click", resetView);
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
fitCamera();
}
window.addEventListener("resize", resize);
resize();
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const delta = Math.min(clock.getDelta(), 0.05);
if (traceRunning) {
traceProgress = (traceProgress + delta * 0.072) % 1;
}
updateCamera();
updateTracer();
renderer.render(scene, camera);
});
</script>
</body>
</html>
```