# Underwater

> The headline ripples as if you are reading it through water.

- Applies to the whole headline
- Live page with controls: https://smthngfun.com/a/underwater
- This style as JSON: https://smthngfun.com/api/styles/underwater
- Every style: https://smthngfun.com/llms.txt

## Settings

The values below are the ones this page was asked for. Change any of them by adding it as a query parameter to the page, to this file or to the JSON address.

| Setting | Parameter | Value | Allowed |
| --- | --- | --- | --- |
| Ripple strength | `strength` | `0.2` | 0.02 to 0.25 em |
| Ripple size | `size` | `2.6` | 0.4 to 3 |
| Time for the current to come round | `cycle` | `3000` | 3000 to 30000 ms |
| Ripples under the cursor | `cursor` | `on` | on, off |
| Water colours | `palette` | `f4fbff-bdefff-7fdcec` | Up to eight six digit hex colours joined with dashes. Empty means off. |

- `t` The headline text to show and to use in the example code.
- `f` A Google font name for the headline, for example Playfair Display.

## Prompt

Written for a coding assistant. It describes the animation fully, so it works without the code below.

```text
Animate the main headline in the hero section of my landing page with an effect called Underwater. Make the headline look as if it is lying just under the surface of moving water. Do it with an SVG filter applied to the heading. The filter makes fractal noise with feTurbulence and uses it in feDisplacementMap to bend the letters, so their edges wobble and flow while the words stay easy to read. Displace by 0.2em, measured against the size of the text, and stretch the noise so the ripples are about 260 percent of the letter height and wider than they are tall. Keep the water moving without a visible loop. Pass the noise through feColorMatrix with type hueRotate and animate its value from 0 to 360 degrees at a steady pace over 3 seconds, repeating forever, so every point circles smoothly and the cycle joins up seamlessly. Also drift the base frequency of the noise slightly up and back over 12.9 seconds, so the pattern does not come back to the same place each time round. Never let the motion reverse or snap. Make the pointer disturb the water. Add a second, finer and faster layer of noise that only shows inside a soft round spot about two letter heights wide, centred on the pointer, and use it for a second displacement on top of the first. Move the spot with the pointer, ease the strength of this second displacement up while the pointer is over the headline, and ease it back to nothing when the pointer leaves, so ripples seem to spread from wherever the pointer touches. Outside the spot the second displacement must be perfectly neutral, so use mid grey there. Give the filter enough margin on every side that displaced edges are not clipped. Fill the letters with a soft horizontal gradient of #f4fbff, #bdefff and #7fdcec using background-clip text, and drift that gradient sideways slowly and seamlessly so the colour seems to move with the current. The text must stay real, selectable text in the page. If the visitor has prefers-reduced-motion turned on, keep the gentle distortion but stop it moving. Keep my existing font, other colours and layout exactly as they are. Screen readers and search engines must still read the headline as one normal sentence, so put the full text in an aria-label on the heading and mark any decorative spans as aria-hidden. If the visitor has prefers-reduced-motion turned on, show the finished headline straight away with no animation. Make sure nothing shifts the layout while it plays. Use plain CSS and a little vanilla JavaScript, unless my project already has an animation library, in which case use that. A live demo with reference code for these exact settings is at https://smthngfun.com/a/underwater and you can use that code as your starting point, adapted to my codebase and styling. If I am happy to credit the source, add a small "Animation by smthngfun" link to https://smthngfun.com in the footer of the page. Ask me before adding it.
```

## Reference code

A working version with the settings above. It assumes the headline has the class `hero-title`. Adapt it to the project's own framework and styling.

```html
<!-- Underwater animation from https://smthngfun.com/a/underwater -->
<h1 class="hero-title">Make your landing page feel alive</h1>
```

```css
.hero-title { position: relative; }
.hero-title .water {
  display: block;
  filter: url(#water); /* the filter is added by the script below */
  background: linear-gradient(100deg, #f4fbff, #bdefff, #7fdcec, #f4fbff) 0 0 / 12em 100%;
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  animation: water-drift 6000ms linear infinite;
}
@keyframes water-drift { to { background-position-x: 12em; } }
@media (prefers-reduced-motion: reduce) {
  .hero-title .water { animation: none; }
}
```

```js
const title = document.querySelector('.hero-title');
const size = parseFloat(getComputedStyle(title).fontSize);
// Ripples are sized against the letters, so the effect looks the same at any font size.
const fx = 0.346 / size;
const fy = fx * 2.4;
const still = matchMedia('(prefers-reduced-motion: reduce)').matches;
const spin = function (ms) {
  return still ? '' : '<animate attributeName="values" from="0" to="360" dur="' + ms + 'ms" repeatCount="indefinite"/>';
};
// A soft round spot. The pointer's ripples only show inside it.
const spot = 'data:image/svg+xml,' + encodeURIComponent(
  "<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><defs><radialGradient id='g'>" +
  "<stop offset='0' stop-color='white'/><stop offset='1' stop-color='white' stop-opacity='0'/></radialGradient></defs>" +
  "<rect width='100' height='100' fill='url(#g)'/></svg>");
const reach = size * 1.1;

title.innerHTML = '<span class="water">' + title.innerHTML + '</span>' +
  '<svg width="0" height="0" style="position:absolute" aria-hidden="true">' +
  '<filter id="water" x="-10%" y="-25%" width="120%" height="150%" color-interpolation-filters="sRGB">' +
  // The current. Rotating the hue of the noise makes every point circle smoothly, with no visible loop.
  '<feTurbulence type="fractalNoise" numOctaves="2" seed="4" baseFrequency="' + fx + ' ' + fy + '" result="noise">' +
  (still ? '' : '<animate attributeName="baseFrequency" dur="12900ms" repeatCount="indefinite" values="' +
    fx + ' ' + fy + ';' + fx * 1.15 + ' ' + fy * 1.1 + ';' + fx + ' ' + fy + '"/>') +
  '</feTurbulence>' +
  '<feColorMatrix in="noise" type="hueRotate" values="0" result="flow">' + spin(3000) + '</feColorMatrix>' +
  '<feDisplacementMap in="SourceGraphic" in2="flow" scale="' + 0.2 * size + '" xChannelSelector="R" yChannelSelector="G" result="base"/>' +
  // The pointer. Finer, faster noise, shown only inside the spot and neutral grey everywhere else.
  '<feTurbulence type="fractalNoise" numOctaves="1" seed="11" baseFrequency="' + fx * 2.6 + ' ' + fy * 2.2 + '" result="fine"/>' +
  '<feColorMatrix in="fine" type="hueRotate" values="0" result="chop">' + spin(900) + '</feColorMatrix>' +
  '<feImage href="' + spot + '" x="-9999" y="-9999" width="' + reach * 2 + '" height="' + reach * 2 + '" preserveAspectRatio="none" result="spot"/>' +
  '<feComposite in="chop" in2="spot" operator="in" result="local"/>' +
  '<feFlood flood-color="rgb(128,128,128)" result="grey"/>' +
  '<feMerge result="map"><feMergeNode in="grey"/><feMergeNode in="local"/></feMerge>' +
  '<feDisplacementMap in="base" in2="map" scale="0" xChannelSelector="R" yChannelSelector="G"/>' +
  '</filter></svg>';

// Follow the pointer and ease the extra ripple in and out.
const water = title.querySelector('.water');
const spotImage = title.querySelector('feImage');
const touch = title.querySelector('feDisplacementMap:last-of-type');
const most = 0.48 * size;
let level = 0;
let goal = 0;
let frame = 0;
function ease() {
  level += (goal - level) * 0.12;
  touch.setAttribute('scale', level * most);
  frame = Math.abs(goal - level) > 0.005 ? requestAnimationFrame(ease) : 0;
}
title.addEventListener('pointermove', function (e) {
  const box = water.getBoundingClientRect();
  spotImage.setAttribute('x', e.clientX - box.left - reach);
  spotImage.setAttribute('y', e.clientY - box.top - reach);
  goal = 1;
  if (!frame) frame = requestAnimationFrame(ease);
});
title.addEventListener('pointerleave', function () {
  goal = 0;
  if (!frame) frame = requestAnimationFrame(ease);
});
```

## Credit

Keep the comment at the top of the code, which reads "Underwater animation from https://smthngfun.com/a/underwater". If the person you are building for is happy to credit the source, add a small visible "Animation by smthngfun" link to https://smthngfun.com in the footer of their page. Ask them first, and do not add it without their say.
