Решение подходит для демонстрационных блоков, баннеров, промо-секций и интерактивных элементов, где важно зафиксировать результат анимации и исключить повторные срабатывания.
Эффект не использует сторонние библиотеки для рендеринга и полностью управляется через JavaScript.
Пример:
HTML:
|
1 2 3 4 5 6 |
<div class="fire-section" id="fire-section"> <div class="fire-title">ТЕКСТ ПОСЛЕ ВЫГОРАНИЯ</div> <img class="fire-bg-image" src="image.webp" alt="background"> <canvas id="fire-overlay"></canvas> </div> <img id="source-image" src="image.webp" crossorigin="anonymous" style="display: none;" alt="source"> |
CSS:
|
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 |
.fire-section { background: #000; position: relative; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; min-height: 520px; margin: 20px 0; cursor: pointer; overflow: hidden; border-radius: 18px; box-shadow: 0 4px 8px rgba(0,0,0,0.15), 0 12px 18px rgba(0,0,0,0.1); z-index: 1; } .fire-title { font-size: var(--fire-font-size, clamp(26px, 5vw, 56px)); line-height: var(--line-height, 1.2); font-weight: 500; font-family: Impact, Charcoal, sans-serif; background: linear-gradient(to bottom, #ff784f 0%, #ff4912 50%, #e82a00 100%); text-shadow: 0 12px 24px rgba(254,117,75, 0.2); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; z-index: 5; position: relative; opacity: 0; } #fire-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 10; } .fire-bg-image { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; filter: grayscale(100%) brightness(0.4) contrast(0.8); z-index: 1; opacity: 0; } .canvas-ready .fire-title, .canvas-ready .fire-bg-image { opacity: 1; } @media screen and (max-width:767px) { .fire-section { min-height: 320px; } } |
JS:
Описание настроек и методов управления анимацией дано в комментариях кода
|
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 |
// ================= НАСТРОЙКИ ================= const FIRE_CONFIG = { // Анимация animation: { duration: 5000, initialProgress: 0.24, autoplay: false, // Автозапуск при загрузке triggerOnScroll: false, // Запуск при скролле в область видимости scrollOffset: 100 // Отступ от края для триггера }, // Текст text: { content: "ТЕКСТ ДО ВЫГОРАНИЯ", // Текст для отображения family: 'Impact, sans-serif', weight: '500', minSize: 26, maxSize: 56, multiplier: { desktop: 0.08, mobile: 0.1 }, lineHeight: 1.2, gradient: ['#fffdfc', '#ffcebf', '#ffa78c'], shadow: { color: 'rgba(0, 0, 0, 0.5)', blur: 24, offsetY: 12 } }, // Визуальные эффекты effects: { fireColor: [6.0, 1.4, 0.0], // RGB множитель для огня burnSpeed: 0.9, // Скорость выгорания noiseScale: 0.75 // Масштаб шума } }; // ================= РАЗБИВКА ТЕКСТА ================= function updateTextLayout() { const titleElement = document.querySelector('.fire-title'); if (!titleElement) return; if (titleElement.querySelector('span')) return; const text = titleElement.textContent.trim(); const words = text.split(' '); if (words.length <= 1) return; titleElement.innerHTML = words.map(word => `<span style="display: block;">${word}</span>` ).join(''); } // ================= ОСНОВНОЙ СКРИПТ ================= // WebGL шейдер (сжатый для производительности) const shader = { vertex: ` #ifdef GL_FRAGMENT_PRECISION_HIGH precision highp float; #else precision mediump float; #endif varying vec2 vUv; attribute vec2 a_position; void main() { vUv = a_position; gl_Position = vec4(a_position, 0.0, 1.0); } `, fragment: ` #ifdef GL_FRAGMENT_PRECISION_HIGH precision highp float; #else precision mediump float; #endif varying vec2 vUv; uniform vec2 u_resolution; uniform float u_progress; uniform float u_time; uniform sampler2D u_texture; // Генератор псевдослучайных чисел float rand(vec2 n) { return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453); } // Шумовая функция (ценный шум) float noise(vec2 n) { const vec2 d = vec2(0., 1.); vec2 b = floor(n); vec2 f = smoothstep(vec2(0.0), vec2(1.0), fract(n)); return mix( mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y ); } // Фрактальный Броуновский шум (fBm) float fbm(vec2 n) { float total = 0.0; float amplitude = 0.4; for (int i = 0; i < 4; i++) { total += noise(n) * amplitude; n += n; amplitude *= 0.6; } return total; } void main() { // UV координаты с коррекцией aspect ratio vec2 uv = vUv; float aspect = u_resolution.x / u_resolution.y; uv.x *= aspect > 1.0 ? 1.0 : aspect; uv.y *= aspect > 1.0 ? 1.0 / aspect : 1.0; // Координаты для текстуры (от -1..1 к 0..1) vec2 screenUv = vUv * 0.5 + 0.5; screenUv.y = 1.0 - screenUv.y; float p = clamp(u_progress, 0.0, 1.0); // Читаем цвет из текстуры vec4 color = texture2D(u_texture, screenUv); // Основной шум для выгорания float main_noise = 1.0 - fbm( ${FIRE_CONFIG.effects.noiseScale} * uv + 10.0 - vec2(0.3, ${FIRE_CONFIG.effects.burnSpeed} * p) ); // Эффект выгорания (пепел) float burn = smoothstep(main_noise - 0.1, main_noise, p); color.rgb -= vec3(0.99, 0.95, 0.99) * burn; // Цвет огня vec3 fire_color = fbm(6.0 * uv - vec2(0.0, 0.005 * u_time)) * vec3(${FIRE_CONFIG.effects.fireColor.join(',')}); // Маска для показа огня float show_fire = smoothstep(0.4, 0.9, fbm(10.0 * uv + 2.0 - vec2(0.0, 0.005 * u_time)) ); // Границы огня float fire_border = 0.02 * show_fire; float fire_edge = smoothstep( main_noise - fire_border, main_noise - 0.5 * fire_border, p ); fire_edge *= (1.0 - smoothstep( main_noise - 0.5 * fire_border, main_noise, p )); // Добавляем огонь color.rgb += fire_color * fire_edge; // Прозрачность (исчезновение) float opacity = 1.0 - smoothstep(main_noise - 0.0005, main_noise, p); gl_FragColor = vec4(color.rgb, opacity); } ` }; // DOM элементы const canvasEl = document.getElementById("fire-overlay"); const section = document.querySelector(".fire-section"); const sourceImage = document.getElementById("source-image"); const dpr = Math.min(window.devicePixelRatio, 2); // Состояние let gl, uniforms, mainTexture; let startTime = 0; let animationProgress = FIRE_CONFIG.animation.initialProgress; let animationFrameId = null; let isAnimating = false; let isBurned = false; let resizeTimeout = null; let scrollTriggered = false; // Инициализация WebGL function initGL() { gl = canvasEl.getContext("webgl"); const vs = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vs, shader.vertex); gl.compileShader(vs); const fs = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fs, shader.fragment); gl.compileShader(fs); const program = gl.createProgram(); gl.attachShader(program, vs); gl.attachShader(program, fs); gl.linkProgram(program); gl.useProgram(program); uniforms = {}; ["u_resolution", "u_progress", "u_time", "u_texture"].forEach(name => { uniforms[name] = gl.getUniformLocation(program, name); }); const buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1,1,-1,-1,1,1,1]), gl.STATIC_DRAW); const pos = gl.getAttribLocation(program, "a_position"); gl.enableVertexAttribArray(pos); gl.vertexAttribPointer(pos, 2, gl.FLOAT, false, 0, 0); } // Создание текстуры function createCombinedTexture(img) { const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); const w = section.offsetWidth; const h = section.offsetHeight; canvas.width = w; canvas.height = h; // Фоновое изображение const ir = img.width / img.height; const sr = w / h; let dw, dh, ox = 0, oy = 0; if (ir > sr) { dh = h; dw = dh * ir; ox = (dw - w) / 2; } else { dw = w; dh = dw / ir; oy = (dh - h) / 2; } ctx.drawImage(img, -ox, -oy, dw, dh); // Текст поверх const isMobile = window.innerWidth <= 768; const multiplier = isMobile ? FIRE_CONFIG.text.multiplier.mobile : FIRE_CONFIG.text.multiplier.desktop; const baseFontSize = w * multiplier; const fontSize = Math.max(FIRE_CONFIG.text.minSize, Math.min(baseFontSize, FIRE_CONFIG.text.maxSize)); const lineHeight = fontSize * FIRE_CONFIG.text.lineHeight; ctx.save(); ctx.font = `${FIRE_CONFIG.text.weight} ${fontSize}px ${FIRE_CONFIG.text.family}`; ctx.textAlign = "center"; ctx.textBaseline = "middle"; // Градиент const gradient = ctx.createLinearGradient(0, 0, 0, h); FIRE_CONFIG.text.gradient.forEach((color, i) => { gradient.addColorStop(i / (FIRE_CONFIG.text.gradient.length - 1), color); }); ctx.fillStyle = gradient; // Тень ctx.shadowColor = FIRE_CONFIG.text.shadow.color; ctx.shadowBlur = FIRE_CONFIG.text.shadow.blur; ctx.shadowOffsetY = FIRE_CONFIG.text.shadow.offsetY; // Многострочный текст const words = FIRE_CONFIG.text.content.split(' '); const x = w / 2; const y = h / 2; let currentY = y - (words.length - 1) * lineHeight / 2; words.forEach(word => { ctx.fillText(word, x, currentY); currentY += lineHeight; }); ctx.restore(); // CSS переменные document.documentElement.style.setProperty('--fire-font-size', `${fontSize}px`); document.documentElement.style.setProperty('--fire-line-height', `${lineHeight}px`); // WebGL текстура const tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, canvas); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); return tex; } // Рендер анимации function render() { if (!isAnimating) return; const elapsed = performance.now() - startTime; const progress = Math.min(elapsed / FIRE_CONFIG.animation.duration, 1); if (progress >= 1) { animationProgress = 1; isAnimating = false; isBurned = true; return; } animationProgress = FIRE_CONFIG.animation.initialProgress + (1 - FIRE_CONFIG.animation.initialProgress) * progress; gl.uniform1f(uniforms.u_time, performance.now()); gl.uniform1f(uniforms.u_progress, animationProgress); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); animationFrameId = requestAnimationFrame(render); } // API функции function startAnimation() { if (isAnimating || isBurned) return; isAnimating = true; startTime = performance.now(); render(); } function restartAnimation() { cancelAnimationFrame(animationFrameId); isAnimating = false; isBurned = false; animationProgress = FIRE_CONFIG.animation.initialProgress; mainTexture = createCombinedTexture(sourceImage); gl.uniform1f(uniforms.u_progress, animationProgress); gl.bindTexture(gl.TEXTURE_2D, mainTexture); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); } // Ресайз с дебаунсом function resize() { if (resizeTimeout) clearTimeout(resizeTimeout); resizeTimeout = setTimeout(() => { canvasEl.width = section.offsetWidth * dpr; canvasEl.height = section.offsetHeight * dpr; gl.viewport(0, 0, canvasEl.width, canvasEl.height); gl.uniform2f( uniforms.u_resolution, canvasEl.width, canvasEl.height ); if (!isAnimating) { mainTexture = createCombinedTexture(sourceImage); gl.bindTexture(gl.TEXTURE_2D, mainTexture); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); } }, 200); } // Проверка видимости для скролла function checkScrollTrigger() { if (scrollTriggered || !FIRE_CONFIG.animation.triggerOnScroll) return; const rect = section.getBoundingClientRect(); const offset = FIRE_CONFIG.animation.scrollOffset; const isVisible = rect.top < window.innerHeight - offset && rect.bottom > offset; if (isVisible && !isBurned) { scrollTriggered = true; startAnimation(); } } // Инициализация function init() { updateTextLayout(); initGL(); resize(); setTimeout(() => { mainTexture = createCombinedTexture(sourceImage); gl.bindTexture(gl.TEXTURE_2D, mainTexture); gl.uniform1f(uniforms.u_progress, animationProgress); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); section.classList.add('canvas-ready'); // Автозапуск if (FIRE_CONFIG.animation.autoplay) { setTimeout(startAnimation, 1000); } }, 100); // Клик по секции section.addEventListener("click", startAnimation); // Ресайз window.addEventListener("resize", resize); // Скролл триггер if (FIRE_CONFIG.animation.triggerOnScroll) { window.addEventListener('scroll', checkScrollTrigger); checkScrollTrigger(); // Проверить сразу } } // Запуск при загрузке DOM if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } // Глобальный API window.fireAnimation = { start: startAnimation, restart: restartAnimation, isBurned: () => isBurned, isAnimating: () => isAnimating, setText: function(newText) { FIRE_CONFIG.text.content = newText; restartAnimation(); }, setConfig: function(newConfig) { Object.assign(FIRE_CONFIG, newConfig); restartAnimation(); } }; |
За основу взято решение, найденное на codepen.io у пользователя Nidal95

Добавить комментарий: