Сетка из 1600 белых кубиков под камерой сверху: курсор пускает по ней круги, гребни волн поднимаются и синеют.
Промпт
Добавь на мою страницу эффект «Поле из кубиков, по которому курсор пускает волны» (по мотивам 3D Wave Grid, автор Franky Hung, туториал на Codrops, лицензия MIT). Ниже готовая страница одним файлом: three.js 0.184.0 через importmap с jsdelivr, без сборщика. Сначала перенеси её как есть и открой через локальный сервер, проведи мышью и убедись, что от курсора расходятся синие круги, и только потом подгоняй.
Как устроен код. Холст `canvas.webgl` лежит на весь экран, поверх него слой `.overlay` с текстом и `pointer-events: none`, чтобы курсор доходил до холста (ссылки внутри снова кликабельны). Сетка — `InstancedMesh` из `GRID × GRID` кубиков `BoxGeometry(0.8, 3, 0.8)`; у каждого экземпляра есть атрибут `aOffset` с его координатами на полу. Камера висит над полем на высоте `RADIUS` и смотрит вниз, функция `placeCamera` слегка поворачивает её за курсором (с плавным догоном 0.04 на кадр). На `pointermove` луч из камеры попадает в невидимую плоскость пола, и если курсор сдвинулся больше чем на `TRAIL_SPACING`, в массив `trail` добавляется точка `{x, z, age, strength}`. Каждый кадр возраст точек растёт, старые удаляются, а все точки пишутся в текстуру `trailTexture` 128×1. Вершинный шейдер подмешан в стандартный `MeshPhongMaterial` через `onBeforeCompile`: только верхняя грань кубика (`position.y > 0`) поднимается на сумму волн от всех точек (кольцо радиусом `uWaveSpeed * age`, гауссово окно ширины `uWaveWidth`, затухание по времени `uFadeTime`), а фрагментный шейдер красит кубик от `COLOR_BASE` к `COLOR_HIGH` по высоте. Та же подмена стоит в `MeshDepthMaterial`, иначе тени не будут следовать за волнами. После рендера идут проходы `EffectComposer`: свой шейдер `VignetteRGBShift` (сдвиг каналов и затемнение к углам) и `OutputPass`. До первого движения мыши работает заставка: в цикле анимации флаг `intro` ведёт виртуальный курсор по восьмёрке через ту же функцию `pointerAt`. После этого через 3 секунды без движения курсора каждые 1.5 секунды в случайную точку падает новая волна (в оригинале автора заставки нет, только случайные волны).
Что менять: цвета `COLOR_BASE` и `COLOR_HIGH` (фон сцены — половина яркости `COLOR_BASE`), размер поля `GRID` и кубиков `CUBE_W`, `GAP`, характер волн в объекте `WAVE` (`amplitude` и `maxHeight` — высота, `speed` — скорость колец, `frequency` — частота гребней, `width` — ширина кольца, `jitter` — неровность), длительность затухания `FADE_TIME`, частоту точек `TRAIL_SPACING`, силу наклона камеры `ALPHA_RANGE` и `BETA_RANGE`, яркость `toneMappingExposure`, силу RGB-сдвига `shiftAmount`. Тексты в `.overlay` замени на свои.
Если проект на React: холст и всю сцену создавай в `useEffect` с пустым списком зависимостей, при размонтировании вызови `renderer.setAnimationLoop(null)`, `renderer.dispose()`, `composer.dispose()`, `geometry.dispose()`, `material.dispose()`, `trailTexture.dispose()` и сними слушатели `resize` и `pointermove`. Текст поверх оставь обычной React-разметкой. Не трогай число 128 в шейдере (оно должно совпадать с `MAX_TRAIL`), не убирай `customDepthMaterial` и проверку `position.y > 0`: без них тени отстают, а кубики растягиваются целиком. При `prefers-reduced-motion` камера не качается, заставки и случайных волн нет, волны идут только от курсора: оставь эту ветку.
Покажи, где на моём сайте такой фон лучше всего смотрится, и подбери цвета под мой бренд.
Код скопируется вместе с промптом
Первый экран портфолио, где вместо фона лежит поле из 40×40 белых кубиков, снятых сверху. Стоит провести мышью, и от курсора по полю расходятся круги, как по воде: кубики на гребне поднимаются, синеют и отбрасывают мягкие тени на соседей, а камера чуть наклоняется вслед за курсором. Пока посетитель не тронул мышь, по полю восьмёркой бежит невидимый курсор, а если мышь потом оставить в покое на три секунды, волны сами падают в случайные точки, так что фон живой и без участия посетителя. По краям кадра цвета чуть расходятся (RGB-сдвиг) и темнеют, это даёт ощущение объектива.
Устроено так: все кубики — один InstancedMesh, поэтому 1600 штук рисуются одним вызовом. Каждое движение курсора превращается лучом в точку на полу, последние 128 точек с их «возрастом» лежат в маленькой текстуре 128×1, а вершинный шейдер для каждого кубика складывает волны от всех точек: кольцо расходится со скоростью 6 единиц в секунду и затухает за пару секунд. Тот же код волн стоит в материале теней, поэтому тени двигаются вместе с кубиками. Подходит для первого экрана студии, портфолио разработчика или дизайнера, страницы продукта в светлом минималистичном стиле. На телефоне волны пускает палец.
Код
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>3D Wave Grid</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap">
<script type="importmap">{ "imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.184.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.184.0/examples/jsm/"
} }</script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
:root { --text: #000; --text-2: #616161; }
html, body { height: 100%; overflow: hidden; background: #808080; font-family: "Inter", sans-serif; color: var(--text); -webkit-font-smoothing: antialiased; }
.webgl { position: fixed; inset: 0; width: 100%; height: 100%; outline: none; touch-action: none; }
/* Text layer above the canvas; it lets the pointer through to the grid */
.overlay { position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column; justify-content: space-between; padding: 2rem; pointer-events: none; }
.overlay a { color: inherit; text-decoration: none; pointer-events: auto; }
.top-nav { position: fixed; top: 0; left: 0; width: 100%; display: flex; gap: 1rem; padding: 1rem; -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); }
.logo { width: 36%; font-size: clamp(3.5rem, 6vw, 5.5rem); font-weight: 700; letter-spacing: -0.04em; line-height: 1; }
.nav { flex: 1; display: flex; gap: .5rem; color: var(--text-2); font-size: 18px; }
.nav div { flex: 1; display: flex; flex-direction: column; gap: .5rem; }
.hero { margin-top: 40vh; display: flex; }
.hero::before { content: ""; width: 36%; }
.hero h1 { flex: 1; max-width: 54%; font-size: clamp(1.5rem, 2.5vw, 2rem); font-weight: 400; }
.hero h1 span { color: var(--text-2); }
.bottom { display: flex; }
.bottom p:first-child { width: 36%; }
.bottom p { flex: 1; }
.reveal { opacity: 0; transform: translateY(20px); animation: reveal 1s cubic-bezier(.215, .61, .355, 1) forwards; animation-delay: calc(.5s + var(--i) * .1s); }
@keyframes reveal { to { opacity: 1; transform: none; } }
@media (max-width: 768px) {
.overlay { padding: 1rem; }
.top-nav { flex-direction: column; align-items: center; }
.logo { width: 100%; text-align: center; font-size: 2rem; }
.nav { width: 100%; font-size: 15px; }
.hero::before { display: none; }
.hero h1 { max-width: none; font-size: 1rem; text-align: center; }
.bottom { font-size: 12px; gap: .5rem; }
}
@media (prefers-reduced-motion: reduce) { .reveal { animation: none; opacity: 1; transform: none; } }
</style>
</head>
<body>
<div class="overlay">
<header class="top-nav">
<a class="logo reveal" style="--i:0" href="#">Studio.dev</a>
<nav class="nav">
<div><a class="reveal" style="--i:1" href="#">Projects</a><a class="reveal" style="--i:1" href="#">About</a><a class="reveal" style="--i:1" href="#">Contact</a></div>
<div><a class="reveal" style="--i:2" href="#">X (Twitter)</a><a class="reveal" style="--i:2" href="#">Instagram</a></div>
<div class="reveal" style="--i:3"><p id="local-time"></p></div>
</nav>
</header>
<section class="hero">
<h1 class="reveal" style="--i:4">A creative developer blending design and technology into memorable experiences.
<span>Work built on clarity, function and emotion.</span></h1>
</section>
<footer class="bottom">
<p class="reveal" style="--i:5">Based anywhere</p>
<p class="reveal" style="--i:6"><a href="#">Check all projects →</a></p>
<p class="reveal" style="--i:7"><a href="#">Contact me →</a></p>
</footer>
</div>
<canvas class="webgl"></canvas>
<script type="module">
// Based on "3D Wave Grid" by Franky Hung (franky-adl), MIT License, Copyright (c) 2026 franky-adl
// https://github.com/franky-adl/3d-wave-grid
import * as THREE from 'three';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
const timeEl = document.getElementById('local-time');
const tick = () => timeEl.textContent = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
tick(); setInterval(tick, 60000);
// Settings
const GRID = 40, CUBE_W = 0.8, CUBE_H = 3, GAP = 0.01;
const WAVE = { amplitude: 0.4, speed: 6.0, frequency: 1.2, width: 3.0, jitter: 0.2, maxHeight: 0.4 };
const COLOR_BASE = '#ffffff', COLOR_HIGH = '#0055ff';
const FADE_TIME = 2.0, TRAIL_SPACING = 0.1, MAX_TRAIL = 128; // MAX_TRAIL must match 128.0 in the shader
const BOUNDS = GRID * (CUBE_W + GAP);
// Renderer, scene, camera
const canvas = document.querySelector('canvas.webgl');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.95;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(COLOR_BASE).multiplyScalar(0.5);
// The camera looks straight down at the grid and orbits a little after the pointer
const camera = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 0.1, 200);
const RADIUS = 12, ALPHA_RANGE = Math.PI * 0.03, BETA_RANGE = Math.PI * 0.05;
const mouse = new THREE.Vector2(), lerpedMouse = new THREE.Vector2();
function placeCamera(mx, my) {
const a = my * ALPHA_RANGE, b = mx * BETA_RANGE;
camera.position.set(-RADIUS * Math.cos(a) * Math.sin(b), RADIUS * Math.cos(a) * Math.cos(b), RADIUS * Math.sin(a));
camera.up.set(0, 0, -1);
camera.lookAt(0, 0, 0);
}
placeCamera(0, 0);
// Lights: key light casts the shadows between the cubes
scene.add(new THREE.AmbientLight('#ffffff', 0.5));
const key = new THREE.DirectionalLight('#ffffff', 4.0);
key.position.set(-20, 10, 6);
key.castShadow = true;
key.shadow.mapSize.set(1024, 1024);
key.shadow.radius = 6;
Object.assign(key.shadow.camera, { near: 0.1, far: 60, left: -22, right: 22, top: 22, bottom: -22 });
key.shadow.bias = 0.0001;
scene.add(key);
const fill = new THREE.DirectionalLight('#ffffff', 1.0);
fill.position.set(10, 5, -3);
scene.add(fill);
// Pointer trail: up to 128 points (x, z, age, strength) in a 128x1 float texture
const trail = [];
const trailData = new Float32Array(MAX_TRAIL * 4);
const trailTexture = new THREE.DataTexture(trailData, MAX_TRAIL, 1, THREE.RGBAFormat, THREE.FloatType);
trailTexture.needsUpdate = true;
const trailUniforms = { uTrailTexture: { value: trailTexture }, uTrailCount: { value: 0 }, uFadeTime: { value: FADE_TIME } };
// Shared by the colour material and the shadow depth material, so shadows follow the waves
function patchVertex(vs) {
return vs.replace('#include <common>', `#include <common>
varying float vHeight;
attribute vec2 aOffset;
uniform sampler2D uTrailTexture;
uniform int uTrailCount;
uniform float uWaveSpeed, uWaveFreq, uWaveWidth, uFadeTime, uAmplitude, uJitter, uMaxHeight;
vec2 hash2(vec2 p) {
p = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)));
return fract(sin(p) * 43758.5453123) - 0.5;
}`).replace('#include <begin_vertex>', `#include <begin_vertex>
vHeight = 0.0;
if (position.y > 0.0) { // only the top face of each cube moves
vec2 worldXZ = aOffset + hash2(aOffset) * uJitter;
float waveHeight = 0.0, totalWeight = 0.0;
for (int i = 0; i < uTrailCount; i++) {
vec4 td = texture2D(uTrailTexture, vec2((float(i) + 0.5) / 128.0, 0.5)); // (x, z, age, strength)
float dist = length(worldXZ - td.rg);
float relDist = dist - uWaveSpeed * td.b; // distance to the expanding ring
float window = exp(-(relDist * relDist) / (uWaveWidth * uWaveWidth));
float weight = exp(-td.b / uFadeTime) * window / (1.0 + dist * 0.1) * td.a;
waveHeight += weight * cos(uWaveFreq * relDist);
totalWeight += weight;
}
waveHeight /= max(totalWeight, 1.0); // overlapping waves average instead of stacking
float displacement = clamp(waveHeight * uAmplitude, -uMaxHeight, uMaxHeight);
transformed.y += displacement;
vHeight = displacement;
}`);
}
function waveUniforms(shader) {
Object.assign(shader.uniforms, trailUniforms, {
uWaveSpeed: { value: WAVE.speed }, uWaveFreq: { value: WAVE.frequency }, uWaveWidth: { value: WAVE.width },
uAmplitude: { value: WAVE.amplitude }, uJitter: { value: WAVE.jitter }, uMaxHeight: { value: WAVE.maxHeight }
});
shader.vertexShader = patchVertex(shader.vertexShader);
}
// 40x40 cubes as one InstancedMesh
const geometry = new THREE.BoxGeometry(CUBE_W, CUBE_H, CUBE_W);
const count = GRID * GRID;
const offsets = new THREE.InstancedBufferAttribute(new Float32Array(count * 2), 2);
geometry.setAttribute('aOffset', offsets);
const material = new THREE.MeshPhongMaterial({ color: 0xffffff });
material.onBeforeCompile = shader => {
waveUniforms(shader);
shader.uniforms.uColorBase = { value: new THREE.Color(COLOR_BASE) };
shader.uniforms.uColorHigh = { value: new THREE.Color(COLOR_HIGH) };
shader.fragmentShader = shader.fragmentShader
.replace('#include <common>', `#include <common>
varying float vHeight; uniform vec3 uColorBase, uColorHigh; uniform float uMaxHeight;`)
.replace('#include <color_fragment>', `#include <color_fragment>
diffuseColor.rgb = mix(uColorBase, uColorHigh, clamp(vHeight / uMaxHeight, 0.0, 1.0));`);
};
const depthMaterial = new THREE.MeshDepthMaterial();
depthMaterial.onBeforeCompile = waveUniforms;
const grid = new THREE.InstancedMesh(geometry, material, count);
grid.customDepthMaterial = depthMaterial;
grid.castShadow = grid.receiveShadow = true;
const dummy = new THREE.Object3D(), spacing = CUBE_W + GAP, half = (GRID - 1) * spacing / 2;
for (let i = 0; i < GRID; i++) for (let j = 0; j < GRID; j++) {
const idx = i * GRID + j, x = i * spacing - half, z = j * spacing - half;
dummy.position.set(x, 0, z); dummy.updateMatrix();
grid.setMatrixAt(idx, dummy.matrix);
offsets.setXY(idx, x, z);
}
scene.add(grid);
// Post-processing: RGB split and darkening towards the corners
const VignetteRGBShift = {
uniforms: { tDiffuse: { value: null }, shiftAmount: { value: 0.005 }, vignetteRadius: { value: 0.3 }, vignetteSoftness: { value: 0.3 } },
vertexShader: `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
fragmentShader: `
uniform sampler2D tDiffuse; uniform float shiftAmount, vignetteRadius, vignetteSoftness; varying vec2 vUv;
void main() {
vec2 q = sign(vUv - 0.5);
float v = smoothstep(vignetteRadius, vignetteRadius + vignetteSoftness, distance(vUv, vec2(0.5)));
vec2 s = shiftAmount * v * q;
vec3 c = vec3(texture2D(tDiffuse, vUv + s).r, texture2D(tDiffuse, vUv).g, texture2D(tDiffuse, vUv - s).b);
gl_FragColor = vec4(c * (1.0 - v * 0.5), 1.0);
}`
};
const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
composer.addPass(new ShaderPass(VignetteRGBShift));
composer.addPass(new OutputPass());
function resize() {
const pr = Math.min(devicePixelRatio, 2);
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(pr); renderer.setSize(innerWidth, innerHeight);
composer.setPixelRatio(pr); composer.setSize(innerWidth, innerHeight);
}
resize();
addEventListener('resize', resize);
// Pointer -> point on the floor plane (raycast), a new trail point every TRAIL_SPACING units
const rayPlane = new THREE.Mesh(new THREE.PlaneGeometry(BOUNDS, BOUNDS), new THREE.MeshBasicMaterial({ visible: false, side: THREE.DoubleSide }));
rayPlane.rotation.x = -Math.PI / 2; rayPlane.updateMatrixWorld(true);
const raycaster = new THREE.Raycaster();
let lastPoint = null, idleTime = 0, randomTimer = 0, randomMode = false, intro = !reduceMotion;
function pushPoint(x, z, strength) {
if (trail.length >= MAX_TRAIL) trail.shift();
trail.push({ x, z, age: 0, strength });
}
function pointerAt(nx, ny) { // nx, ny: normalized screen coords [-1, 1]
mouse.set(nx, ny);
raycaster.setFromCamera(mouse, camera);
const hit = raycaster.intersectObject(rayPlane)[0];
if (!hit) return;
const { x, z } = hit.point;
let d = 0;
if (lastPoint) { d = Math.hypot(x - lastPoint.x, z - lastPoint.z); if (d < TRAIL_SPACING) return; }
pushPoint(x, z, d);
lastPoint = { x, z };
idleTime = 0; randomTimer = 0; randomMode = false;
}
addEventListener('pointermove', e => { intro = false; pointerAt(e.clientX / innerWidth * 2 - 1, -(e.clientY / innerHeight) * 2 + 1); });
// Animation loop
let prev = performance.now();
renderer.setAnimationLoop(now => {
const delta = Math.min((now - prev) / 1000, 0.1);
prev = now;
// intro autoplay until the first real pointer move: a virtual cursor glides in a figure-eight
if (intro) { const t = now / 1000; pointerAt(Math.sin(t * 1.6) * 0.7, Math.sin(t * 3.2) * 0.5); }
if (!reduceMotion) {
lerpedMouse.x += (mouse.x - lerpedMouse.x) * 0.04;
lerpedMouse.y += (mouse.y - lerpedMouse.y) * 0.04;
placeCamera(lerpedMouse.x, lerpedMouse.y);
}
// age the points, drop the ones that have faded out
for (let i = trail.length - 1; i >= 0; i--) if ((trail[i].age += delta) > FADE_TIME * 4) trail.splice(i, 1);
// after 3 s without the pointer, drop a random wave every 1.5 s
idleTime += delta;
if (!reduceMotion && idleTime >= 3 && !randomMode) { randomMode = true; randomTimer = 0; }
if (randomMode && (randomTimer += delta) >= 1.5) {
pushPoint((Math.random() - 0.5) * 0.5 * BOUNDS, (Math.random() - 0.5) * 0.5 * BOUNDS, 0.8 + Math.random() * 0.2);
randomTimer = 0;
}
trail.forEach((p, i) => trailData.set([p.x, p.z, p.age, p.strength], i * 4));
trailTexture.needsUpdate = true;
trailUniforms.uTrailCount.value = trail.length;
composer.render();
});
</script>
</body>
</html>