Prompt specification
Build or customize the Three.js 3D scene "Scatterplot point cloud and fitted line" 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: Scatterplot point cloud and fitted line
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/scatterplot-point-cloud-and-fitted-line-x1785
Scene Description Prompt:
I'd like to see this as a low-poly Three.js scene: scatterplot point cloud and fitted line. Build a three-dimensional display of a two-variable synthetic scatterplot with a regression line and residual segments; keep the plotted data on a clear common plane. Use cdnjs and return one self-contained HTML file.
Working Three.js Starter (scatterplot-point-cloud-and-fitted-line-x1785):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Low-Poly Regression Scene</title>
<style>
:root {
color-scheme: dark;
--bg: #07111d;
--panel: rgba(13, 28, 44, 0.78);
--panel-border: rgba(160, 211, 235, 0.16);
--text: #edf8ff;
--muted: #91aabd;
--cyan: #64dcff;
--coral: #ff8b73;
--lime: #b8ff72;
--amber: #ffc857;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 72% 38%, rgba(37, 97, 125, 0.25), transparent 34%),
radial-gradient(circle at 12% 85%, rgba(77, 45, 112, 0.18), transparent 32%),
linear-gradient(145deg, #07111d 0%, #091725 48%, #07101a 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#app {
position: relative;
width: 100%;
height: 100%;
isolation: isolate;
}
#app::after {
content: "";
position: absolute;
inset: 0;
z-index: 2;
pointer-events: none;
background: radial-gradient(circle at center, transparent 48%, rgba(0, 0, 0, 0.24) 100%);
}
canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
canvas.dragging {
cursor: grabbing;
}
.hud {
position: absolute;
inset: 0;
z-index: 5;
pointer-events: none;
}
header {
position: absolute;
top: 24px;
left: 26px;
max-width: 570px;
}
.eyebrow {
margin-bottom: 8px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(28px, 3.2vw, 50px);
font-weight: 720;
line-height: 1.02;
letter-spacing: -0.045em;
text-shadow: 0 5px 30px rgba(0, 0, 0, 0.28);
}
.subtitle {
max-width: 500px;
margin: 12px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.controls {
position: absolute;
top: 24px;
right: 24px;
display: flex;
gap: 8px;
pointer-events: auto;
}
button {
min-height: 38px;
padding: 0 14px;
border: 1px solid var(--panel-border);
border-radius: 10px;
background: rgba(12, 27, 42, 0.78);
color: var(--text);
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
backdrop-filter: blur(14px);
transition: border-color 160ms ease, background 160ms ease, transform 160ms ease;
}
button:hover {
border-color: rgba(100, 220, 255, 0.5);
background: rgba(20, 43, 61, 0.9);
transform: translateY(-1px);
}
button:active {
transform: translateY(0);
}
button:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
.stats {
position: absolute;
top: 150px;
left: 26px;
width: 250px;
padding: 17px;
border: 1px solid var(--panel-border);
border-radius: 15px;
background: var(--panel);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(18px);
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 14px;
color: #cfe4ef;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.seed {
color: #658092;
font-variant-numeric: tabular-nums;
letter-spacing: 0.08em;
}
.equation {
margin-bottom: 15px;
padding: 11px 12px;
border: 1px solid rgba(184, 255, 114, 0.17);
border-radius: 10px;
background: rgba(184, 255, 114, 0.055);
color: var(--lime);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 13px;
white-space: nowrap;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.metric {
min-height: 68px;
padding: 10px;
border: 1px solid rgba(157, 196, 219, 0.1);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.metric-label {
display: block;
margin-bottom: 5px;
color: #70899a;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric-value {
color: #edf8ff;
font-size: 20px;
font-weight: 720;
font-variant-numeric: tabular-nums;
}
.plane-note {
display: flex;
align-items: center;
gap: 8px;
margin-top: 13px;
color: #7f98aa;
font-size: 10px;
line-height: 1.4;
}
.plane-note::before {
content: "";
width: 7px;
height: 7px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px rgba(100, 220, 255, 0.75);
}
.legend {
position: absolute;
right: 24px;
bottom: 24px;
display: grid;
gap: 9px;
min-width: 188px;
padding: 14px 16px;
border: 1px solid var(--panel-border);
border-radius: 13px;
background: var(--panel);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(18px);
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
color: #b9ccd8;
font-size: 11px;
}
.swatch {
width: 17px;
height: 7px;
border-radius: 99px;
background: currentColor;
box-shadow: 0 0 12px color-mix(in srgb, currentColor 35%, transparent);
}
.swatch.point {
width: 9px;
height: 9px;
border-radius: 2px;
transform: rotate(25deg);
}
.hint {
position: absolute;
bottom: 25px;
left: 26px;
color: #698296;
font-size: 10px;
letter-spacing: 0.04em;
}
.hint strong {
color: #a7bdca;
font-weight: 700;
}
#labels {
position: absolute;
inset: 0;
z-index: 4;
overflow: hidden;
pointer-events: none;
}
.axis-label,
.tick-label {
position: absolute;
left: 0;
top: 0;
color: #8da8b9;
font-size: 10px;
font-weight: 650;
font-variant-numeric: tabular-nums;
text-shadow: 0 1px 5px #06101a;
will-change: transform;
}
.axis-label {
color: #d6eaf4;
font-size: 13px;
font-weight: 800;
letter-spacing: 0.06em;
}
#tooltip {
position: fixed;
z-index: 20;
display: none;
min-width: 172px;
padding: 11px 13px;
border: 1px solid rgba(142, 202, 232, 0.25);
border-radius: 10px;
background: rgba(7, 17, 29, 0.93);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.35);
color: #dcecf4;
font-size: 11px;
line-height: 1.55;
pointer-events: none;
backdrop-filter: blur(12px);
}
#tooltip b {
color: var(--cyan);
}
@media (max-width: 760px) {
header {
top: 18px;
left: 18px;
right: 18px;
}
h1 {
max-width: 330px;
font-size: 31px;
}
.subtitle {
display: none;
}
.controls {
top: auto;
right: 14px;
bottom: 14px;
}
button {
min-height: 34px;
padding: 0 10px;
font-size: 10px;
}
.stats {
top: 112px;
left: 14px;
width: 220px;
padding: 13px;
}
.metric {
min-height: 58px;
padding: 8px;
}
.metric-value {
font-size: 17px;
}
.legend {
right: 14px;
bottom: 58px;
min-width: 155px;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<main id="app">
<canvas id="scene" aria-label="Interactive three-dimensional scatterplot with regression and residuals"></canvas>
<div id="labels" aria-hidden="true"></div>
<div class="hud">
<header>
<div class="eyebrow">Low-poly statistics / interactive scene</div>
<h1>Regression,<br />in three dimensions.</h1>
<p class="subtitle">
A synthetic two-variable sample constrained to one common plane. Faceted points show the
observations, the bright line is the least-squares fit, and amber segments mark residuals.
</p>
</header>
<section class="stats" aria-label="Regression statistics">
<div class="panel-title">
<span>Model summary</span>
<span class="seed" id="seedValue">SEED 1042</span>
</div>
<div class="equation" id="equation">y = 0.82x + 0.18</div>
<div class="metric-grid">
<div class="metric">
<span class="metric-label">Samples</span>
<span class="metric-value" id="sampleCount">54</span>
</div>
<div class="metric">
<span class="metric-label">R²</span>
<span class="metric-value" id="rSquared">0.72</span>
</div>
<div class="metric">
<span class="metric-label">RMSE</span>
<span class="metric-value" id="rmse">0.48</span>
</div>
<div class="metric">
<span class="metric-label">Slope</span>
<span class="metric-value" id="slope">0.82</span>
</div>
</div>
<div class="plane-note">All observations share the same analytical plane: z = 0.</div>
</section>
<div class="controls">
<button id="resample" type="button">New sample</button>
<button id="toggleResiduals" type="button">Hide residuals</button>
<button id="resetView" type="button">Reset view</button>
</div>
<section class="legend" aria-label="Scene legend">
<div class="legend-row" style="color: var(--lime)">
<span class="swatch"></span>
<span>Least-squares fit</span>
</div>
<div class="legend-row" style="color: var(--amber)">
<span class="swatch"></span>
<span>Residual segment</span>
</div>
<div class="legend-row" style="color: var(--cyan)">
<span class="swatch point"></span>
<span>Observation below fit</span>
</div>
<div class="legend-row" style="color: var(--coral)">
<span class="swatch point"></span>
<span>Observation above fit</span>
</div>
</section>
<div class="hint"><strong>Drag</strong> to orbit · <strong>Scroll / pinch</strong> to zoom · hover a point</div>
</div>
<div id="tooltip" role="status"></div>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const labelLayer = document.querySelector("#labels");
const tooltip = document.querySelector("#tooltip");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0x07111d, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(39, 1, 0.1, 100);
const ambient = new THREE.HemisphereLight(0xc9efff, 0x182334, 2.1);
scene.add(ambient);
const keyLight = new THREE.DirectionalLight(0xe9f8ff, 3.2);
keyLight.position.set(5, 8, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
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 = 30;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x58caff, 1.1);
rimLight.position.set(-6, -3, 5);
scene.add(rimLight);
const COLORS = {
plane: 0x10283a,
gridMinor: 0x36556a,
gridMajor: 0x52738a,
axis: 0x9db9c9,
fit: 0xb8ff72,
residual: 0xffc857,
below: 0x64dcff,
above: 0xff8b73
};
const LIMITS = {
xMin: -3.2,
xMax: 3.2,
yMin: -3.05,
yMax: 3.25
};
const plotPlane = new THREE.Mesh(
new THREE.PlaneGeometry(
LIMITS.xMax - LIMITS.xMin,
LIMITS.yMax - LIMITS.yMin
),
new THREE.MeshStandardMaterial({
color: COLORS.plane,
roughness: 0.88,
metalness: 0.03,
transparent: true,
opacity: 0.88,
side: THREE.DoubleSide,
depthWrite: false
})
);
plotPlane.position.z = -0.018;
plotPlane.receiveShadow = true;
scene.add(plotPlane);
const borderGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(LIMITS.xMin, LIMITS.yMin, 0.008),
new THREE.Vector3(LIMITS.xMax, LIMITS.yMin, 0.008),
new THREE.Vector3(LIMITS.xMax, LIMITS.yMax, 0.008),
new THREE.Vector3(LIMITS.xMin, LIMITS.yMax, 0.008),
new THREE.Vector3(LIMITS.xMin, LIMITS.yMin, 0.008)
]);
const border = new THREE.Line(
borderGeometry,
new THREE.LineBasicMaterial({
color: 0x7896a8,
transparent: true,
opacity: 0.58
})
);
scene.add(border);
function addGrid() {
const minor = [];
const major = [];
for (let x = LIMITS.xMin; x <= LIMITS.xMax + 0.001; x += 0.5) {
const target = Number.isInteger(x) ? major : minor;
target.push(
x, LIMITS.yMin, 0.006,
x, LIMITS.yMax, 0.006
);
}
for (let y = LIMITS.yMin; y <= LIMITS.yMax + 0.001; y += 0.5) {
const target = Number.isInteger(y) ? major : minor;
target.push(
LIMITS.xMin, y, 0.006,
LIMITS.xMax, y, 0.006
);
}
const minorGeometry = new THREE.BufferGeometry();
minorGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(minor, 3)
);
const majorGeometry = new THREE.BufferGeometry();
majorGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(major, 3)
);
const minorLines = new THREE.LineSegments(
minorGeometry,
new THREE.LineBasicMaterial({
color: COLORS.gridMinor,
transparent: true,
opacity: 0.18,
depthWrite: false
})
);
const majorLines = new THREE.LineSegments(
majorGeometry,
new THREE.LineBasicMaterial({
color: COLORS.gridMajor,
transparent: true,
opacity: 0.34,
depthWrite: false
})
);
minorLines.renderOrder = 1;
majorLines.renderOrder = 1;
scene.add(minorLines, majorLines);
}
addGrid();
const axisMaterial = new THREE.MeshStandardMaterial({
color: COLORS.axis,
roughness: 0.55,
metalness: 0.08,
flatShading: true
});
function cylinderBetween(start, end, radius, material, radialSegments = 8) {
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(
radius,
radius,
length,
radialSegments,
1,
false
);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
return mesh;
}
scene.add(
cylinderBetween(
new THREE.Vector3(LIMITS.xMin, LIMITS.yMin, 0.035),
new THREE.Vector3(LIMITS.xMax, LIMITS.yMin, 0.035),
0.018,
axisMaterial
),
cylinderBetween(
new THREE.Vector3(LIMITS.xMin, LIMITS.yMin, 0.035),
new THREE.Vector3(LIMITS.xMin, LIMITS.yMax, 0.035),
0.018,
axisMaterial
)
);
for (let x = -3; x <= 3; x++) {
scene.add(
cylinderBetween(
new THREE.Vector3(x, LIMITS.yMin, 0.036),
new THREE.Vector3(x, LIMITS.yMin - 0.11, 0.036),
0.011,
axisMaterial,
6
)
);
}
for (let y = -3; y <= 3; y++) {
scene.add(
cylinderBetween(
new THREE.Vector3(LIMITS.xMin, y, 0.036),
new THREE.Vector3(LIMITS.xMin - 0.11, y, 0.036),
0.011,
axisMaterial,
6
)
);
}
const dynamicGroup = new THREE.Group();
let residualGroup = new THREE.Group();
dynamicGroup.add(residualGroup);
scene.add(dynamicGroup);
let pointMeshes = [];
let residualMaterial;
let fitMaterial;
let currentData = [];
let regression = null;
let hoveredPoint = null;
let sampleSeed = 1042;
const pointGeometry = new THREE.IcosahedronGeometry(0.09, 0);
pointGeometry.userData.persistent = true;
function mulberry32(seed) {
return function random() {
let value = seed += 0x6D2B79F5;
value = Math.imul(value ^ value >>> 15, value | 1);
value ^= value + Math.imul(value ^ value >>> 7, value | 61);
return ((value ^ value >>> 14) >>> 0) / 4294967296;
};
}
function generateData(seed) {
const random = mulberry32(seed);
const points = [];
const count = 54;
for (let i = 0; i < count; i++) {
const x = (random() * 2 - 1) * 2.45;
// Approximately normal noise, scaled for a visually clear relationship.
const noise =
(random() + random() + random() + random() - 2) * 0.47;
const y = 0.18 + 0.82 * x + noise;
points.push({ x, y });
}
return points;
}
function fitLinearRegression(points) {
const n = points.length;
const meanX = points.reduce((sum, p) => sum + p.x, 0) / n;
const meanY = points.reduce((sum, p) => sum + p.y, 0) / n;
let numerator = 0;
let denominator = 0;
for (const point of points) {
numerator += (point.x - meanX) * (point.y - meanY);
denominator += (point.x - meanX) ** 2;
}
const slope = numerator / denominator;
const intercept = meanY - slope * meanX;
let sse = 0;
let sst = 0;
for (const point of points) {
const fitted = intercept + slope * point.x;
const residual = point.y - fitted;
sse += residual * residual;
sst += (point.y - meanY) ** 2;
}
return {
slope,
intercept,
rSquared: 1 - sse / sst,
rmse: Math.sqrt(sse / n)
};
}
function clearDynamicGroup() {
dynamicGroup.traverse((object) => {
if (object.geometry && !object.geometry.userData.persistent) {
object.geometry.dispose();
}
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
for (const material of materials) {
material.dispose();
}
}
});
dynamicGroup.clear();
residualGroup = new THREE.Group();
dynamicGroup.add(residualGroup);
pointMeshes = [];
}
function updateStats() {
document.querySelector("#seedValue").textContent =
`SEED ${sampleSeed}`;
document.querySelector("#sampleCount").textContent =
currentData.length;
document.querySelector("#rSquared").textContent =
regression.rSquared.toFixed(2);
document.querySelector("#rmse").textContent =
regression.rmse.toFixed(2);
document.querySelector("#slope").textContent =
regression.slope.toFixed(2);
document.querySelector("#equation").textContent =
`y = ${regression.slope.toFixed(2)}x ${regression.intercept >= 0 ? "+" : "−"} ` +
`${Math.abs(regression.intercept).toFixed(2)}`;
}
function buildScene() {
clearDynamicGroup();
currentData = generateData(sampleSeed);
regression = fitLinearRegression(currentData);
updateStats();
const birthTime = performance.now();
fitMaterial = new THREE.MeshStandardMaterial({
color: COLORS.fit,
emissive: 0x355d15,
emissiveIntensity: 0.75,
roughness: 0.38,
metalness: 0.08,
flatShading: true,
transparent: true,
opacity: 0
});
residualMaterial = new THREE.MeshStandardMaterial({
color: COLORS.residual,
emissive: 0x6c3c00,
emissiveIntensity: 0.5,
roughness: 0.5,
metalness: 0.04,
flatShading: true,
transparent: true,
opacity: 0
});
const fitStart = new THREE.Vector3(
LIMITS.xMin,
regression.intercept + regression.slope * LIMITS.xMin,
0.075
);
const fitEnd = new THREE.Vector3(
LIMITS.xMax,
regression.intercept + regression.slope * LIMITS.xMax,
0.075
);
const fitLine = cylinderBetween(
fitStart,
fitEnd,
0.032,
fitMaterial,
8
);
fitLine.castShadow = true;
dynamicGroup.add(fitLine);
currentData.forEach((point, index) => {
const fitted = regression.intercept + regression.slope * point.x;
const residual = point.y - fitted;
const color = residual >= 0 ? COLORS.above : COLORS.below;
const material = new THREE.MeshStandardMaterial({
color,
emissive: new THREE.Color(color).multiplyScalar(0.09),
emissiveIntensity: 0.8,
roughness: 0.58,
metalness: 0.04,
flatShading: true
});
const mesh = new THREE.Mesh(pointGeometry, material);
mesh.position.set(point.x, point.y, 0.075);
mesh.rotation.set(
randomRotation(index * 3.1),
randomRotation(index * 1.7 + 0.4),
randomRotation(index * 2.3 + 1.2)
);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.scale.setScalar(0.001);
mesh.userData = {
pointIndex: index,
bornAt: birthTime + index * 13,
baseEmissive: new THREE.Color(color).multiplyScalar(0.09),
hoverScale: 1
};
pointMeshes.push(mesh);
dynamicGroup.add(mesh);
const residualStart = new THREE.Vector3(point.x, fitted, 0.075);
const residualEnd = new THREE.Vector3(point.x, point.y, 0.075);
const segment = cylinderBetween(
residualStart,
residualEnd,
0.013,
residualMaterial,
6
);
segment.userData.bornAt = birthTime + 240 + index * 7;
residualGroup.add(segment);
});
}
function randomRotation(value) {
return (Math.sin(value * 12.9898) * 0.5 + 0.5) * Math.PI;
}
// Camera controls are implemented directly without external addons.
const view = {
theta: 0.73,
phi: 0.83,
radius: 10.7,
target: new THREE.Vector3(-0.72, -0.12, 0)
};
const defaultView = {
theta: view.theta,
phi: view.phi,
radius: view.radius,
target: view.target.clone()
};
function updateCamera() {
const sinPhi = Math.sin(view.phi);
camera.position.set(
view.target.x + view.radius * sinPhi * Math.sin(view.theta),
view.target.y + view.radius * sinPhi * Math.cos(view.theta),
view.target.z + view.radius * Math.cos(view.phi)
);
camera.lookAt(view.target);
}
function resetView() {
view.theta = defaultView.theta;
view.phi = defaultView.phi;
view.radius = defaultView.radius;
view.target.copy(defaultView.target);
updateCamera();
}
const pointers = new Map();
let lastPinchDistance = 0;
let dragged = false;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY,
startX: event.clientX,
startY: event.clientY
});
dragged = false;
canvas.classList.add("dragging");
if (pointers.size === 2) {
lastPinchDistance = pointerDistance();
}
});
function pointerDistance() {
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("pointermove", (event) => {
const previous = pointers.get(event.pointerId);
if (!previous) {
updateHover(event);
return;
}
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
pointers.set(event.pointerId, {
...previous,
x: event.clientX,
y: event.clientY
});
if (pointers.size === 2) {
const distance = pointerDistance();
if (lastPinchDistance > 0 && distance > 0) {
view.radius = THREE.MathUtils.clamp(
view.radius * (lastPinchDistance / distance),
6.5,
18
);
updateCamera();
}
lastPinchDistance = distance;
dragged = true;
return;
}
if (Math.abs(event.clientX - previous.startX) +
Math.abs(event.clientY - previous.startY) > 2) {
dragged = true;
}
view.theta -= dx * 0.006;
view.phi = THREE.MathUtils.clamp(view.phi + dy * 0.006, 0.28, 1.43);
updateCamera();
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) {
lastPinchDistance = 0;
}
if (pointers.size === 0) {
canvas.classList.remove("dragging");
window.setTimeout(() => { dragged = false; }, 0);
}
}
canvas.addEventListener("pointerup", releasePointer);
canvas.addEventListener("pointercancel", releasePointer);
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
view.radius = THREE.MathUtils.clamp(
view.radius * Math.exp(event.deltaY * 0.001),
6.5,
18
);
updateCamera();
}, { passive: false });
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function updateHover(event) {
if (dragged || event.pointerType === "touch") return;
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObjects(pointMeshes, false)[0];
setHoveredPoint(hit ? hit.object : null);
if (hit) {
const point = currentData[hit.object.userData.pointIndex];
const fitted = regression.intercept + regression.slope * point.x;
const residual = point.y - fitted;
tooltip.innerHTML = `
<div><b>Observation ${hit.object.userData.pointIndex + 1}</b></div>
<div>x₁ = ${point.x.toFixed(3)}</div>
<div>x₂ = ${point.y.toFixed(3)}</div>
<div>residual = ${residual >= 0 ? "+" : "−"}${Math.abs(residual).toFixed(3)}</div>
`;
tooltip.style.display = "block";
tooltip.style.left =
`${Math.min(event.clientX + 16, window.innerWidth - 205)}px`;
tooltip.style.top =
`${Math.min(event.clientY + 14, window.innerHeight - 130)}px`;
} else {
tooltip.style.display = "none";
}
}
function setHoveredPoint(mesh) {
if (hoveredPoint === mesh) return;
if (hoveredPoint) {
hoveredPoint.userData.hoverScale = 1;
hoveredPoint.material.emissive.copy(
hoveredPoint.userData.baseEmissive
);
}
hoveredPoint = mesh;
if (hoveredPoint) {
hoveredPoint.userData.hoverScale = 1.35;
hoveredPoint.material.emissive.set(0xffffff);
hoveredPoint.material.emissiveIntensity = 0.34;
}
}
canvas.addEventListener("pointerleave", () => {
setHoveredPoint(null);
tooltip.style.display = "none";
});
document.querySelector("#resample").addEventListener("click", () => {
sampleSeed += 97;
buildScene();
});
document.querySelector("#resetView").addEventListener("click", resetView);
document.querySelector("#toggleResiduals").addEventListener("click", (event) => {
residualGroup.visible = !residualGroup.visible;
event.currentTarget.textContent =
residualGroup.visible ? "Hide residuals" : "Show residuals";
});
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") resetView();
if (event.key.toLowerCase() === "h") {
residualGroup.visible = !residualGroup.visible;
document.querySelector("#toggleResiduals").textContent =
residualGroup.visible ? "Hide residuals" : "Show residuals";
}
});
// Projected DOM labels keep the chart crisp without loading font or text addons.
const projectedLabels = [];
function addLabel(text, position, className = "tick-label") {
const element = document.createElement("div");
element.className = className;
element.textContent = text;
labelLayer.appendChild(element);
projectedLabels.push({ element, position });
}
for (let x = -3; x <= 3; x++) {
addLabel(
String(x),
new THREE.Vector3(x, LIMITS.yMin - 0.24, 0.04)
);
}
for (let y = -3; y <= 3; y++) {
addLabel(
String(y),
new THREE.Vector3(LIMITS.xMin - 0.25, y, 0.04)
);
}
addLabel(
"PREDICTOR X₁",
new THREE.Vector3(2.35, LIMITS.yMin - 0.62, 0.04),
"axis-label"
);
addLabel(
"RESPONSE X₂",
new THREE.Vector3(LIMITS.xMin - 0.66, 2.75, 0.04),
"axis-label"
);
const projectedPosition = new THREE.Vector3();
function updateLabels() {
for (const item of projectedLabels) {
projectedPosition.copy(item.position).project(camera);
const visible =
projectedPosition.z > -1 &&
projectedPosition.z < 1 &&
Math.abs(projectedPosition.x) < 1.25 &&
Math.abs(projectedPosition.y) < 1.25;
item.element.style.display = visible ? "block" : "none";
if (!visible) continue;
const x = (projectedPosition.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projectedPosition.y * 0.5 + 0.5) * window.innerHeight;
item.element.style.transform =
`translate(${x}px, ${y}px) translate(-50%, -50%)`;
}
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
const clock = new THREE.Clock();
const reducedMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
function easeOutBack(value) {
const c1 = 1.70158;
const c3 = c1 + 1;
return 1 + c3 * (value - 1) ** 3 + c1 * (value - 1) ** 2;
}
function animate(now) {
requestAnimationFrame(animate);
const time = now * 0.001;
if (fitMaterial) {
const progress = reducedMotion
? 1
: THREE.MathUtils.clamp((now - buildSceneStart) / 500, 0, 1);
fitMaterial.opacity = progress;
}
if (residualMaterial) {
const progress = reducedMotion
? 1
: THREE.MathUtils.clamp((now - buildSceneStart - 180) / 650, 0, 1);
residualMaterial.opacity = progress * 0.88;
}
for (const mesh of pointMeshes) {
const progress = reducedMotion
? 1
: THREE.MathUtils.clamp(
(now - mesh.userData.bornAt) / 420,
0,
1
);
const scale = Math.max(0.001, easeOutBack(progress));
mesh.scale.setScalar(scale * mesh.userData.hoverScale);
if (hoveredPoint === mesh) {
mesh.rotation.y += 0.018;
mesh.rotation.x += 0.006;
}
}
camera.updateMatrixWorld();
updateLabels();
renderer.render(scene, camera);
}
let buildSceneStart = performance.now();
buildScene();
buildSceneStart = performance.now();
resize();
updateCamera();
requestAnimationFrame(animate);
</script>
</body>
</html>
```