Prompt specification
Build or customize the Three.js 3D scene "Chocolate snap and layered bar" 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: Chocolate snap and layered bar
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/chocolate-snap-and-layered-bar-x0089
Scene Description Prompt:
Please use Three.js from cdnjs for a stylized scene based on this idea: chocolate snap and layered bar. Build a segmented chocolate bar with one broken piece exposing its thickness and smooth fracture; use molded ridges and separate wrapper folds for readable structure. Return one self-contained HTML file.
Working Three.js Starter (chocolate-snap-and-layered-bar-x0089):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SNAP — Stylized Chocolate Study</title>
<style>
:root {
color-scheme: light;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e8d7c3;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
.title {
position: fixed;
top: 30px;
left: 34px;
z-index: 2;
color: #35170f;
pointer-events: none;
user-select: none;
}
.title .eyebrow {
margin-bottom: 8px;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.24em;
opacity: 0.56;
}
.title h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(38px, 5vw, 68px);
font-weight: 500;
line-height: 0.88;
letter-spacing: -0.055em;
}
.title p {
margin: 14px 0 0;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.14em;
text-transform: uppercase;
opacity: 0.55;
}
.caption {
position: fixed;
right: 28px;
bottom: 25px;
z-index: 2;
max-width: 260px;
padding: 12px 15px;
border: 1px solid rgba(67, 31, 20, 0.13);
border-radius: 999px;
color: rgba(56, 27, 17, 0.68);
background: rgba(255, 248, 239, 0.38);
backdrop-filter: blur(10px);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.1em;
text-align: center;
text-transform: uppercase;
pointer-events: none;
user-select: none;
}
.vignette {
position: fixed;
inset: 0;
z-index: 1;
pointer-events: none;
background:
radial-gradient(circle at 52% 46%, transparent 48%, rgba(83, 47, 27, 0.08) 100%);
mix-blend-mode: multiply;
}
@media (max-width: 700px) {
.title {
top: 22px;
left: 22px;
}
.title p {
display: none;
}
.caption {
right: 50%;
bottom: 18px;
transform: translateX(50%);
white-space: nowrap;
}
}
</style>
</head>
<body>
<div class="title">
<div class="eyebrow">Chocolate study · No. 01</div>
<h1>SNAP</h1>
<p>Drag to orbit · Scroll to zoom · Double-click to reset</p>
</div>
<div class="vignette"></div>
<div class="caption">Embossed segments / satin fracture / folded foil</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8d7c3);
scene.fog = new THREE.Fog(0xe8d7c3, 20, 34);
const camera = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(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 stylized chocolate bar scene");
document.body.prepend(renderer.domElement);
const target = new THREE.Vector3(-0.25, 0.12, 0.05);
let desiredTheta = 0.56;
let desiredPhi = 1.02;
let desiredRadius = 16.2;
let currentTheta = desiredTheta;
let currentPhi = desiredPhi;
let currentRadius = desiredRadius;
const clock = new THREE.Clock();
function randomGenerator(seed) {
return function () {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const random = randomGenerator(48291);
function createNoiseTexture(size = 256, low = 205, high = 255) {
const canvas = document.createElement("canvas");
canvas.width = canvas.height = size;
const ctx = canvas.getContext("2d");
const image = ctx.createImageData(size, size);
for (let i = 0; i < image.data.length; i += 4) {
const value = Math.floor(THREE.MathUtils.lerp(low, high, random()));
image.data[i] = value;
image.data[i + 1] = value;
image.data[i + 2] = value;
image.data[i + 3] = 255;
}
ctx.putImageData(image, 0, 0);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(1.8, 1.8);
texture.anisotropy = Math.min(4, renderer.capabilities.getMaxAnisotropy());
return texture;
}
function createWrapperTexture() {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 512;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#741a35";
ctx.fillRect(0, 0, 1024, 512);
for (let i = 0; i < 650; i++) {
const x = random() * 1024;
const y = random() * 512;
const length = 15 + random() * 70;
ctx.strokeStyle = random() > 0.5
? "rgba(255,220,175,0.025)"
: "rgba(20,0,12,0.045)";
ctx.lineWidth = 0.5 + random() * 1.4;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + length, y + (random() - 0.5) * 8);
ctx.stroke();
}
const gold = "#d8ae55";
ctx.strokeStyle = gold;
ctx.lineWidth = 8;
ctx.beginPath();
ctx.moveTo(0, 28);
ctx.lineTo(1024, 28);
ctx.moveTo(0, 484);
ctx.lineTo(1024, 484);
ctx.stroke();
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(0, 45);
ctx.lineTo(1024, 45);
ctx.moveTo(0, 467);
ctx.lineTo(1024, 467);
ctx.stroke();
ctx.fillStyle = "rgba(239,201,112,0.88)";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "700 70px Georgia";
ctx.fillText("SNAP", 512, 250);
ctx.font = "600 24px sans-serif";
ctx.letterSpacing = "10px";
ctx.fillText("CACAO • 72%", 512, 320);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.wrapS = texture.wrapT = THREE.ClampToEdgeWrapping;
texture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
return texture;
}
function createShadowTexture() {
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 256;
const ctx = canvas.getContext("2d");
const gradient = ctx.createRadialGradient(128, 128, 12, 128, 128, 124);
gradient.addColorStop(0, "rgba(35,13,7,0.48)");
gradient.addColorStop(0.48, "rgba(35,13,7,0.22)");
gradient.addColorStop(1, "rgba(35,13,7,0)");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 256, 256);
return new THREE.CanvasTexture(canvas);
}
const chocolateNoise = createNoiseTexture();
const fractureNoise = createNoiseTexture(256, 220, 255);
const wrapperTexture = createWrapperTexture();
const topChocolate = new THREE.MeshPhysicalMaterial({
color: 0x512117,
map: chocolateNoise,
roughness: 0.34,
metalness: 0,
clearcoat: 0.26,
clearcoatRoughness: 0.42
});
const sideChocolate = new THREE.MeshPhysicalMaterial({
color: 0x30130d,
map: chocolateNoise,
roughness: 0.43,
metalness: 0,
clearcoat: 0.12,
clearcoatRoughness: 0.5
});
const ridgeMaterial = new THREE.MeshPhysicalMaterial({
color: 0x642b1d,
map: chocolateNoise,
roughness: 0.31,
clearcoat: 0.22,
clearcoatRoughness: 0.4
});
const fractureMaterial = new THREE.MeshPhysicalMaterial({
color: 0x713b29,
map: fractureNoise,
roughness: 0.48,
clearcoat: 0.08,
side: THREE.DoubleSide
});
const fractureEdgeMaterial = new THREE.MeshStandardMaterial({
color: 0x32140d,
roughness: 0.58
});
const wrapperMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
map: wrapperTexture,
roughness: 0.69,
metalness: 0.04,
side: THREE.DoubleSide
});
const goldMaterial = new THREE.MeshPhysicalMaterial({
color: 0xd7a642,
roughness: 0.31,
metalness: 0.62,
clearcoat: 0.28,
clearcoatRoughness: 0.3,
side: THREE.DoubleSide
});
const goldCreaseMaterial = new THREE.MeshStandardMaterial({
color: 0x826022,
roughness: 0.44,
metalness: 0.48
});
function roundedRectPath(w, h, r, PathType = THREE.Shape) {
const path = new PathType();
const x = -w / 2;
const y = -h / 2;
path.moveTo(x + r, y);
path.lineTo(x + w - r, y);
path.quadraticCurveTo(x + w, y, x + w, y + r);
path.lineTo(x + w, y + h - r);
path.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
path.lineTo(x + r, y + h);
path.quadraticCurveTo(x, y + h, x, y + h - r);
path.lineTo(x, y + r);
path.quadraticCurveTo(x, y, x + r, y);
path.closePath();
return path;
}
function makeChocolateBlockGeometry(w, d) {
const shape = roundedRectPath(w, d, 0.19);
const geometry = new THREE.ExtrudeGeometry(shape, {
depth: 0.47,
bevelEnabled: true,
bevelSegments: 4,
steps: 1,
bevelSize: 0.055,
bevelThickness: 0.06,
curveSegments: 10
});
geometry.rotateX(-Math.PI / 2);
geometry.computeVertexNormals();
return geometry;
}
function makeRidgeGeometry(w, d) {
const outer = roundedRectPath(w, d, 0.15);
outer.holes.push(roundedRectPath(w - 0.13, d - 0.13, 0.11, THREE.Path));
const geometry = new THREE.ExtrudeGeometry(outer, {
depth: 0.018,
bevelEnabled: true,
bevelSegments: 2,
steps: 1,
bevelSize: 0.014,
bevelThickness: 0.014,
curveSegments: 8
});
geometry.rotateX(-Math.PI / 2);
return geometry;
}
const SEGMENT_W = 2.06;
const SEGMENT_D = 0.98;
const blockGeometry = makeChocolateBlockGeometry(SEGMENT_W, SEGMENT_D);
const ridgeGeometry = makeRidgeGeometry(SEGMENT_W - 0.18, SEGMENT_D - 0.18);
const ovalGeometry = new THREE.TorusGeometry(0.105, 0.025, 8, 28);
function addMolding(group) {
const ridge = new THREE.Mesh(ridgeGeometry, ridgeMaterial);
ridge.position.y = 0.526;
ridge.castShadow = true;
ridge.receiveShadow = true;
group.add(ridge);
const oval = new THREE.Mesh(ovalGeometry, ridgeMaterial);
oval.rotation.x = -Math.PI / 2;
oval.scale.set(1.38, 0.72, 1);
oval.position.y = 0.555;
oval.castShadow = true;
group.add(oval);
}
const xPositions = [-3.45, -1.15, 1.15, 3.45];
const zPositions = [-1.13, 0, 1.13];
for (let column = 0; column < xPositions.length; column++) {
for (let row = 0; row < zPositions.length; row++) {
// The front-right segment is the detached broken piece.
if (column === 3 && row === 2) continue;
const group = new THREE.Group();
group.position.set(xPositions[column], 0, zPositions[row]);
const body = new THREE.Mesh(blockGeometry, [topChocolate, sideChocolate]);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
addMolding(group);
scene.add(group);
}
}
function makeSheet(pointFunction, nx = 24, nz = 16) {
const positions = [];
const uvs = [];
const indices = [];
for (let iz = 0; iz <= nz; iz++) {
const u = iz / nz;
for (let ix = 0; ix <= nx; ix++) {
const t = ix / nx;
const [x, y, z] = pointFunction(t, u);
positions.push(x, y, z);
uvs.push(t, u);
}
}
for (let iz = 0; iz < nz; iz++) {
for (let ix = 0; ix < nx; ix++) {
const a = iz * (nx + 1) + ix;
const b = a + 1;
const c = a + nx + 1;
const d = c + 1;
indices.push(a, c, b, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
const underWrapper = new THREE.Mesh(
makeSheet((t, u) => {
const x = THREE.MathUtils.lerp(-5.4, 4.85, t);
const z = THREE.MathUtils.lerp(-2.38, 2.48, u);
const y = -0.13 + 0.025 * Math.sin(t * Math.PI * 3) * Math.sin(u * Math.PI);
return [x, y, z];
}, 34, 18),
wrapperMaterial
);
underWrapper.castShadow = true;
underWrapper.receiveShadow = true;
scene.add(underWrapper);
function makeGoldTrim(z0, z1) {
const trim = new THREE.Mesh(
makeSheet((t) => {
const x = THREE.MathUtils.lerp(-5.1, 4.65, t);
return [x, -0.073, THREE.MathUtils.lerp(z0, z1, 0.5)];
}, 32, 1),
goldMaterial
);
trim.castShadow = true;
trim.receiveShadow = true;
scene.add(trim);
}
makeGoldTrim(2.25, 2.32);
makeGoldTrim(-2.32, -2.25);
function leftFlapPoint(t, u) {
const fold = Math.sin(t * Math.PI * 4);
const x =
THREE.MathUtils.lerp(-4.42, -7.18, t) +
0.14 * fold * (u - 0.5);
const y =
-0.09 +
0.91 * t +
0.2 * fold * (0.65 + 0.35 * Math.sin(u * Math.PI));
const z =
THREE.MathUtils.lerp(-2.13, 2.28, u) +
0.08 * Math.sin(t * Math.PI * 3) * Math.sin(u * Math.PI);
return [x, y, z];
}
const leftFlap = new THREE.Mesh(
makeSheet(leftFlapPoint, 38, 18),
goldMaterial
);
leftFlap.castShadow = true;
leftFlap.receiveShadow = true;
scene.add(leftFlap);
function rightFlapPoint(t, u) {
const fold = Math.sin(t * Math.PI * 3.5);
const x =
THREE.MathUtils.lerp(4.32, 7.42, t) +
0.13 * fold * (u - 0.5);
const y = -0.08 + 0.42 * t + 0.15 * Math.sin(t * Math.PI * 4);
const z =
THREE.MathUtils.lerp(-1.92, 2.58, u) +
0.12 * Math.sin(t * Math.PI * 2);
return [x, y, z];
}
const rightFlap = new THREE.Mesh(
makeSheet(rightFlapPoint, 32, 18),
goldMaterial
);
rightFlap.castShadow = true;
rightFlap.receiveShadow = true;
scene.add(rightFlap);
function addCreases(pointFunction, times, material) {
for (const t of times) {
const points = [];
for (let i = 0; i <= 12; i++) {
const [x, y, z] = pointFunction(t, i / 12);
points.push(new THREE.Vector3(x, y + 0.006, z));
}
const curve = new THREE.CatmullRomCurve3(points);
const crease = new THREE.Mesh(
new THREE.TubeGeometry(curve, 28, 0.008, 5, false),
material
);
crease.castShadow = true;
scene.add(crease);
}
}
addCreases(
leftFlapPoint,
[0.17, 0.34, 0.51, 0.68, 0.85],
goldCreaseMaterial
);
addCreases(
rightFlapPoint,
[0.19, 0.42, 0.66, 0.84],
goldCreaseMaterial
);
const fractureContour = [
[-0.435, -0.018],
[0.425, -0.008],
[0.475, 0.085],
[0.455, 0.405],
[0.365, 0.505],
[-0.375, 0.495],
[-0.475, 0.385],
[-0.455, 0.085]
];
function makeFractureGeometry(outwardSide) {
const shape = new THREE.Shape();
fractureContour.forEach(([x, y], index) => {
if (index === 0) shape.moveTo(x, y);
else shape.lineTo(x, y);
});
shape.closePath();
const geometry = new THREE.ShapeGeometry(shape, 10);
if (geometry.index && outwardSide > 0) {
const index = geometry.index;
for (let i = 0; i < index.count; i += 3) {
const a = index.getX(i);
const b = index.getX(i + 1);
const c = index.getX(i + 2);
index.setX(i, a);
index.setX(i + 1, c);
index.setX(i + 2, b);
}
}
const position = geometry.attributes.position;
for (let i = 0; i < position.count; i++) {
const z = position.getX(i);
const y = position.getY(i);
const subtleWarp =
0.004 * Math.sin(z * 19 + y * 11) +
0.002 * Math.cos(y * 27 - z * 7);
position.setXYZ(i, subtleWarp, y, z);
}
position.needsUpdate = true;
geometry.computeVertexNormals();
geometry.computeBoundingSphere();
return geometry;
}
function createFracture(x, z, outwardSide, parent = null) {
const group = new THREE.Group();
group.position.set(x, 0, z);
const face = new THREE.Mesh(
makeFractureGeometry(outwardSide),
fractureMaterial
);
face.castShadow = true;
face.receiveShadow = true;
group.add(face);
const edgePoints = fractureContour.map(([pz, py]) => {
return new THREE.Vector3(outwardSide * 0.009, py, pz);
});
const edgeCurve = new THREE.CatmullRomCurve3(edgePoints, true, "centripetal");
const edge = new THREE.Mesh(
new THREE.TubeGeometry(edgeCurve, 48, 0.012, 6, true),
fractureEdgeMaterial
);
edge.castShadow = true;
group.add(edge);
if (parent) parent.add(group);
else scene.add(group);
return group;
}
// The exposed interior face left on the main bar.
createFracture(2.24, zPositions[2], 1);
const brokenPiece = new THREE.Group();
brokenPiece.position.set(5.52, 0.035, 1.5);
brokenPiece.rotation.set(0.02, 2.62, -0.045);
const brokenBody = new THREE.Mesh(
blockGeometry,
[topChocolate, sideChocolate]
);
brokenBody.castShadow = true;
brokenBody.receiveShadow = true;
brokenPiece.add(brokenBody);
addMolding(brokenPiece);
// Its original left edge is now turned toward the viewer.
createFracture(-(SEGMENT_W / 2 + 0.058), 0, -1, brokenPiece);
scene.add(brokenPiece);
const crumbGeometry = new THREE.IcosahedronGeometry(0.085, 1);
const crumbMaterial = new THREE.MeshStandardMaterial({
color: 0x4b1d13,
map: chocolateNoise,
roughness: 0.57
});
const crumbPositions = [
[2.55, 1.92, 0.065],
[2.77, 2.04, 0.05],
[3.03, 1.96, 0.045],
[4.32, 1.98, 0.055],
[4.57, 2.12, 0.047],
[4.78, 1.92, 0.06],
[4.98, 2.15, 0.042],
[5.22, 2.04, 0.052],
[5.48, 2.25, 0.038],
[5.78, 2.05, 0.05],
[6.03, 2.19, 0.035],
[2.18, 1.92, 0.04],
[3.92, 1.88, 0.045]
];
for (let i = 0; i < crumbPositions.length; i++) {
const crumb = new THREE.Mesh(crumbGeometry, crumbMaterial);
crumb.position.set(...crumbPositions[i]);
crumb.scale.set(
0.65 + random() * 0.75,
0.45 + random() * 0.7,
0.6 + random() * 0.8
);
crumb.rotation.set(random() * 3, random() * 3, random() * 3);
crumb.castShadow = true;
crumb.receiveShadow = true;
scene.add(crumb);
}
const dustPositions = [];
for (let i = 0; i < 150; i++) {
const x = THREE.MathUtils.lerp(-4.8, 6.4, random());
const z = THREE.MathUtils.lerp(-2.15, 2.3, random());
dustPositions.push(x, -0.058 + random() * 0.02, z);
}
const dustGeometry = new THREE.BufferGeometry();
dustGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(dustPositions, 3)
);
const dust = new THREE.Points(
dustGeometry,
new THREE.PointsMaterial({
color: 0x3e180f,
size: 0.022,
transparent: true,
opacity: 0.38,
depthWrite: false
})
);
scene.add(dust);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
new THREE.MeshStandardMaterial({
color: 0xd8c3aa,
roughness: 0.93,
metalness: 0
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.28;
floor.receiveShadow = true;
scene.add(floor);
const contactShadow = new THREE.Mesh(
new THREE.PlaneGeometry(13.8, 5.4),
new THREE.MeshBasicMaterial({
map: createShadowTexture(),
transparent: true,
opacity: 0.54,
depthWrite: false
})
);
contactShadow.rotation.x = -Math.PI / 2;
contactShadow.position.set(-0.15, -0.271, 0);
scene.add(contactShadow);
const hemisphere = new THREE.HemisphereLight(0xfff4e5, 0x755344, 1.75);
scene.add(hemisphere);
const key = new THREE.DirectionalLight(0xfff0da, 3.7);
key.position.set(-4.5, 10, 7.5);
key.castShadow = true;
key.shadow.mapSize.set(2048, 2048);
key.shadow.camera.left = -10;
key.shadow.camera.right = 10;
key.shadow.camera.top = 9;
key.shadow.camera.bottom = -9;
key.shadow.camera.near = 1;
key.shadow.camera.far = 28;
key.shadow.bias = -0.0002;
key.shadow.normalBias = 0.025;
scene.add(key);
const fill = new THREE.DirectionalLight(0xc9ddff, 1.25);
fill.position.set(9, 5, -8);
scene.add(fill);
const rim = new THREE.DirectionalLight(0xffc989, 1.05);
rim.position.set(-8, 4, -4);
scene.add(rim);
const fractureLight = new THREE.PointLight(0xffc797, 18, 9, 2);
fractureLight.position.set(4.8, 4.2, 4.6);
scene.add(fractureLight);
function updateCamera() {
const spherical = new THREE.Spherical(
currentRadius,
currentPhi,
currentTheta
);
camera.position.copy(target).add(
new THREE.Vector3().setFromSpherical(spherical)
);
camera.lookAt(target);
}
updateCamera();
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
desiredTheta -= dx * 0.0052;
desiredPhi = THREE.MathUtils.clamp(
desiredPhi - dy * 0.0045,
0.34,
1.38
);
});
function endDrag(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
desiredRadius = THREE.MathUtils.clamp(
desiredRadius * Math.exp(event.deltaY * 0.001),
10.5,
23
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
desiredTheta = 0.56;
desiredPhi = 1.02;
desiredRadius = innerWidth / innerHeight < 0.85 ? 18 : 16.2;
});
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
function resize() {
camera.aspect = innerWidth / innerHeight;
camera.fov = camera.aspect < 0.85 ? 52 : 40;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
}
addEventListener("resize", resize);
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const smoothing = 1 - Math.exp(-dt * 7.5);
currentTheta = THREE.MathUtils.lerp(currentTheta, desiredTheta, smoothing);
currentPhi = THREE.MathUtils.lerp(currentPhi, desiredPhi, smoothing);
currentRadius = THREE.MathUtils.lerp(currentRadius, desiredRadius, smoothing);
updateCamera();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```