-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShaderFX.js
More file actions
447 lines (392 loc) · 15.9 KB
/
Copy pathShaderFX.js
File metadata and controls
447 lines (392 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
import * as THREE from 'three';
// ─── Vertex ───────────────────────────────────────────────────────────────────
const VERT = /* glsl */`
varying vec2 vUv;
varying vec2 vMouse;
void main() {
vUv = uv;
gl_Position = vec4(position, 1.0);
}
`;
// ─── Общие uniforms для всех эффектов ────────────────────────────────────────
// tMap — исходная текстура (картинка)
// time — время (постоянно растёт)
// prog — прогресс эффекта 0→1 (hover in/out, scroll, etc.)
// mouse — позиция мыши в UV (0..1)
// res — размер элемента в пикселях
const HEAD = /* glsl */`
precision highp float;
uniform sampler2D tMap;
uniform float time;
uniform float prog;
uniform vec2 mouse;
uniform vec2 res;
varying vec2 vUv;
`;
// ─── Эффекты — каждый работает с одной текстурой tMap ────────────────────────
export const EFFECTS = {
// Без эффекта
none: `
void main() { gl_FragColor = texture2D(tMap, vUv); }`,
// Волна (prog — интенсивность)
wave: `
void main() {
vec2 uv = vUv;
uv.x += sin(uv.y * 10.0 + time * 3.0) * 0.02 * prog;
uv.y += cos(uv.x * 10.0 + time * 2.5) * 0.015 * prog;
gl_FragColor = texture2D(tMap, uv);
}`,
// Рябь от мыши
ripple: `
void main() {
vec2 uv = vUv;
float dist = distance(uv, mouse);
float wave = sin(dist * 30.0 - time * 5.0) * 0.02 * prog;
wave *= smoothstep(0.5, 0.0, dist);
uv += normalize(uv - mouse) * wave;
gl_FragColor = texture2D(tMap, uv);
}`,
// Глитч
glitch: `
float rand(vec2 co) { return fract(sin(dot(co, vec2(12.9898,78.233))) * 43758.5453); }
void main() {
vec2 uv = vUv;
float t = floor(time * 10.0) / 10.0;
float glAmt = prog * 0.08;
float slice = floor(uv.y / 0.1);
float rnd = rand(vec2(slice, t));
uv.x += (rnd - 0.5) * glAmt * step(0.85, rand(vec2(t, slice)));
vec4 col = texture2D(tMap, uv);
col.r = texture2D(tMap, uv + vec2(glAmt * 0.5 * prog, 0.0)).r;
col.b = texture2D(tMap, uv - vec2(glAmt * 0.5 * prog, 0.0)).b;
gl_FragColor = col;
}`,
// RGB split (хроматик аберрация)
'rgb-split': `
void main() {
float amt = prog * 0.015;
vec2 uv = vUv;
vec2 dir = normalize(uv - vec2(0.5));
float r = texture2D(tMap, uv + dir * amt ).r;
float g = texture2D(tMap, uv ).g;
float b = texture2D(tMap, uv - dir * amt ).b;
float a = texture2D(tMap, uv ).a;
gl_FragColor = vec4(r, g, b, a);
}`,
// Пикселизация
pixelize: `
void main() {
float px = mix(1.0, 60.0, prog);
vec2 size = res / px;
vec2 uv = (floor(vUv * size) + 0.5) / size;
gl_FragColor = texture2D(tMap, uv);
}`,
// Zoom distortion от мыши
zoom: `
void main() {
vec2 uv = vUv;
float dist = distance(uv, mouse);
float lens = prog * 0.3 * smoothstep(0.4, 0.0, dist);
uv = mix(uv, mouse, lens);
gl_FragColor = texture2D(tMap, uv);
}`,
// Шум (зернистость)
noise: `
float rand(vec2 co) { return fract(sin(dot(co, vec2(12.9898,78.233))) * 43758.5453); }
void main() {
vec4 col = texture2D(tMap, vUv);
float n = (rand(vUv + time * 0.01) - 0.5) * prog * 0.15;
gl_FragColor = vec4(col.rgb + n, col.a);
}`,
// Жидкость (fluid warp)
fluid: `
void main() {
vec2 uv = vUv;
float t = time * 0.5;
vec2 off = vec2(
sin(uv.y * 4.0 + t) * cos(uv.x * 3.0 + t * 0.7),
cos(uv.x * 4.0 + t) * sin(uv.y * 3.0 + t * 0.8)
) * 0.025 * prog;
gl_FragColor = texture2D(tMap, uv + off);
}`,
// Distortion следующий за мышью
'mouse-distort': `
void main() {
vec2 uv = vUv;
vec2 dir = uv - mouse;
float dist = length(dir);
float pull = prog * 0.15 * smoothstep(0.35, 0.0, dist);
uv -= normalize(dir) * pull * (1.0 - dist / 0.35);
gl_FragColor = texture2D(tMap, uv);
}`,
// Барьерное искажение при скролле
'scroll-warp': `
void main() {
vec2 uv = vUv;
uv.x += sin(uv.y * 6.28 + time) * 0.04 * prog;
uv.y += cos(uv.x * 6.28) * 0.02 * prog;
gl_FragColor = texture2D(tMap, uv);
}`,
// Reveal — появление через шум
reveal: `
float rand(vec2 co){ return fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453); }
void main() {
float n = rand(floor(vUv * 40.0));
float alpha = smoothstep(n - 0.1, n + 0.1, prog);
gl_FragColor = vec4(texture2D(tMap, vUv).rgb, alpha);
}`,
// Свечение краёв
'edge-glow': `
void main() {
vec2 px = 1.0 / res;
float dx = length(vec2(
texture2D(tMap, vUv+vec2(px.x,0)).r - texture2D(tMap, vUv-vec2(px.x,0)).r,
texture2D(tMap, vUv+vec2(0,px.y)).r - texture2D(tMap, vUv-vec2(0,px.y)).r
));
vec4 col = texture2D(tMap, vUv);
col.rgb += vec3(dx * 8.0 * prog);
gl_FragColor = col;
}`,
};
// ─────────────────────────────────────────────────────────────────────────────
/**
* ShaderFX — шейдерный эффект на любой DOM-элемент
*
* Использование:
*
* import ShaderFX from './ShaderFX.js'
*
* // На img
* new ShaderFX('#hero', { effect: 'wave', trigger: 'hover' })
*
* // На div с background или вложенным img
* new ShaderFX('.card', { effect: 'ripple', trigger: 'hover' })
*
* // Постоянная анимация
* new ShaderFX('.banner', { effect: 'fluid', trigger: 'auto' })
*
* // При скролле мимо элемента
* new ShaderFX('.section-bg', { effect: 'scroll-warp', trigger: 'scroll' })
*
* // Появление через шум при скролле
* new ShaderFX('.photo', { effect: 'reveal', trigger: 'scroll' })
*
* // Свой GLSL
* new ShaderFX('.el', { effect: myGLSL, trigger: 'hover' })
*
* // Несколько элементов сразу
* ShaderFX.applyAll('.card img', { effect: 'glitch', trigger: 'hover' })
*/
// ─────────────────────────────────────────────────────────────────────────────
export default class ShaderFX {
constructor(target, options = {}) {
const el = typeof target === 'string'
? document.querySelector(target)
: target;
if (!el) { console.warn('ShaderFX: element not found', target); return; }
const {
effect = 'wave',
trigger = 'hover', // 'hover' | 'scroll' | 'auto' | 'click' | 'always'
duration = 600, // мс анимации прогресса
strength = 1.0, // множитель интенсивности (0..2)
} = options;
this._el = el;
this._duration = duration;
this._strength = strength;
this._trigger = trigger;
this._prog = 0;
this._raf = null;
// Найти src картинки
const imgSrc = this._findImageSrc(el);
if (!imgSrc) { console.warn('ShaderFX: no image source found in', el); return; }
this._setup(el, imgSrc, effect);
this._bindTrigger(trigger);
}
// ─── Найти src ────────────────────────────────────────────────────────────
_findImageSrc(el) {
if (el.tagName === 'IMG') return el.src;
const img = el.querySelector('img');
if (img) return img.src;
const bg = getComputedStyle(el).backgroundImage;
const m = bg.match(/url\(["']?(.+?)["']?\)/);
return m ? m[1] : null;
}
// ─── Three.js setup ───────────────────────────────────────────────────────
_setup(el, imgSrc, effect) {
const rect = el.getBoundingClientRect();
const w = rect.width || el.offsetWidth || 300;
const h = rect.height || el.offsetHeight || 200;
// Renderer
this._renderer = new THREE.WebGLRenderer({ antialias: false, alpha: true });
this._renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
this._renderer.setSize(w, h);
const canvas = this._renderer.domElement;
Object.assign(canvas.style, {
position: 'absolute',
inset: '0',
width: '100%',
height: '100%',
pointerEvents: 'none', // клики проходят сквозь canvas
});
// Контейнер должен быть position:relative/absolute
const pos = getComputedStyle(el).position;
if (pos === 'static') el.style.position = 'relative';
// Если target это <img> — оборачиваем в div
if (el.tagName === 'IMG') {
const wrap = document.createElement('div');
Object.assign(wrap.style, {
position: 'relative',
display: 'inline-block',
width: el.offsetWidth + 'px',
height: el.offsetHeight + 'px',
});
el.parentNode.insertBefore(wrap, el);
wrap.appendChild(el);
wrap.appendChild(canvas);
this._el = wrap;
} else {
el.appendChild(canvas);
}
// Scene
this._scene = new THREE.Scene();
this._camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
this._uniforms = {
tMap: { value: null },
time: { value: 0 },
prog: { value: 0 },
mouse: { value: new THREE.Vector2(0.5, 0.5) },
res: { value: new THREE.Vector2(w, h) },
};
const frag = EFFECTS[effect] ?? effect;
const mat = new THREE.ShaderMaterial({
uniforms: this._uniforms,
vertexShader: VERT,
fragmentShader: HEAD + frag,
transparent: true,
});
this._mesh = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), mat);
this._scene.add(this._mesh);
// Загружаем текстуру
new THREE.TextureLoader().load(imgSrc, tex => {
tex.colorSpace = THREE.SRGBColorSpace;
this._uniforms.tMap.value = tex;
this._startLoop();
});
// Resize
this._onResize = () => {
const r = this._el.getBoundingClientRect();
this._renderer.setSize(r.width, r.height);
this._uniforms.res.value.set(r.width, r.height);
};
window.addEventListener('resize', this._onResize);
}
// ─── Render loop ──────────────────────────────────────────────────────────
_startLoop() {
const tick = () => {
this._raf = requestAnimationFrame(tick);
this._uniforms.time.value += 0.016;
this._uniforms.prog.value = this._prog * this._strength;
this._renderer.render(this._scene, this._camera);
};
tick();
}
// ─── Анимация прогресса ───────────────────────────────────────────────────
_animateTo(target) {
const start = this._prog;
const t0 = performance.now();
const ease = t => t < .5 ? 2*t*t : -1+(4-2*t)*t;
const step = () => {
const raw = Math.min((performance.now() - t0) / this._duration, 1);
this._prog = start + (target - start) * ease(raw);
if (raw < 1) requestAnimationFrame(step);
};
requestAnimationFrame(step);
}
// ─── Привязка триггеров ───────────────────────────────────────────────────
_bindTrigger(trigger) {
const el = this._el;
if (trigger === 'hover') {
el.addEventListener('mouseenter', () => this._animateTo(1));
el.addEventListener('mouseleave', () => this._animateTo(0));
}
if (trigger === 'click') {
let on = false;
el.addEventListener('click', () => {
on = !on;
this._animateTo(on ? 1 : 0);
});
}
if (trigger === 'auto' || trigger === 'always') {
// прогресс осциллирует 0→1→0 по синусу — живая анимация
// переопределяем prog прямо в loop
const origLoop = this._startLoop.bind(this);
this._startLoop = () => {
const tick = () => {
this._raf = requestAnimationFrame(tick);
this._uniforms.time.value += 0.016;
// плавная пульсация
this._uniforms.prog.value = (.5 + .5 * Math.sin(this._uniforms.time.value)) * this._strength;
this._renderer.render(this._scene, this._camera);
};
tick();
};
}
if (trigger === 'scroll') {
this._onScroll = () => {
const rect = this._el.getBoundingClientRect();
const vh = window.innerHeight;
// 0 когда элемент только вошёл в экран, 1 когда полностью виден
const p = Math.max(0, Math.min(1,
1 - (rect.top) / (vh * 0.6)
));
this._prog = p;
};
window.addEventListener('scroll', this._onScroll, { passive: true });
this._onScroll(); // проверить сразу
}
if (trigger === 'scroll-in') {
// Однократно: элемент вошёл в экран → анимируем 0→1
const obs = new IntersectionObserver(entries => {
entries.forEach(e => {
if (e.isIntersecting) { this._animateTo(1); obs.disconnect(); }
});
}, { threshold: 0.2 });
obs.observe(this._el);
}
// Mouse tracking (работает для всех триггеров — обогащает ripple/zoom/distort)
el.addEventListener('mousemove', e => {
const rect = el.getBoundingClientRect();
this._uniforms.mouse.value.set(
(e.clientX - rect.left) / rect.width,
1 - (e.clientY - rect.top) / rect.height // Y инвертирован в GL
);
});
}
// ─── Публичное API ────────────────────────────────────────────────────────
/** Сменить эффект на лету */
setEffect(effect) {
const frag = EFFECTS[effect] ?? effect;
this._mesh.material = new THREE.ShaderMaterial({
uniforms: this._uniforms,
vertexShader: VERT,
fragmentShader: HEAD + frag,
transparent: true,
});
}
/** Принудительно установить прогресс */
setProgress(value) { this._prog = Math.max(0, Math.min(1, value)); }
destroy() {
cancelAnimationFrame(this._raf);
window.removeEventListener('resize', this._onResize);
window.removeEventListener('scroll', this._onScroll);
this._uniforms.tMap.value?.dispose();
this._mesh.material.dispose();
this._renderer.dispose();
this._renderer.domElement.remove();
}
// ─── Статический хелпер: применить ко всем элементам по селектору ─────────
static applyAll(selector, options = {}) {
return [...document.querySelectorAll(selector)]
.map(el => new ShaderFX(el, options));
}
}