Flowing lines
A calm ribbon of fine lines drawn on a canvas, flowing behind a section and parting around the cursor. It rests when it is off screen. Sits well behind a closing call to action.
A calm ribbon of fine lines drawn on a canvas, flowing behind a section and parting around the cursor. It rests when it is off screen. Sits well behind a closing call to action.
/**
* MIT License
*
* Copyright (c) 2025 kokonutUI
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Rewritten for Tastebud in plain React and CSS, without Tailwind or framer-motion.
*/
"use client";
import { type CSSProperties, type ReactNode, useEffect, useRef } from "react";
import st from "./ribbon-lines.module.css";
export interface RibbonLinesProps {
className?: string;
/** Inline style for the box, such as its height. */
style?: CSSProperties;
/** Content shown over the lines. */
children?: ReactNode;
/** Number of lines, shared across the three depth layers. */
count?: number;
/** How far the ribbon fans out, as a share of the height. */
spread?: number;
/** Tilt of the ribbon, in degrees. */
angle?: number;
/** How fast the ribbon flows. 0 holds it still. */
speed?: number;
/** Part the lines around the cursor. */
interactive?: boolean;
/** Colour of the lines. Any CSS colour; "currentColor" follows the text. */
color?: string;
/** A second colour for the front layer only. Leave it out for one colour. */
frontColor?: string;
/** Figma black behind the lines instead of white. */
dark?: boolean;
}
const SAMPLES = 64;
/** Lines reach this far past each side, so their ends never show. */
const OVERSCAN = 0.06;
const DRAW_MS = 1400;
const DRAW_STAGGER_MS = 40;
const PART_RADIUS = 150;
const PART_PUSH = 56;
interface Layer {
width: number;
opacity: number;
/** Phase offset, so the layers don't sit on top of each other. */
phase: number;
/** Flow speed relative to the others: the front layer moves fastest. */
pace: number;
/** How much the cursor parts this layer. */
part: number;
}
const LAYERS: Layer[] = [
{ width: 1, opacity: 0.22, phase: 0.6, pace: 0.7, part: 0.45 },
{ width: 1.25, opacity: 0.34, phase: 0.3, pace: 0.85, part: 0.75 },
{ width: 1.5, opacity: 0.55, phase: 0, pace: 1, part: 1 },
];
interface Pointer {
x: number;
y: number;
/** Eases to 1 while the mouse is over the hero, back to 0 when it leaves. */
amount: number;
on: boolean;
}
interface Frame {
width: number;
height: number;
time: number;
/** 0 to 1: how much of each line the entrance has drawn. */
drawn: number[];
pointer: Pointer;
}
interface Shape {
count: number;
spread: number;
slope: number;
interactive: boolean;
}
/**
* Height of line `s` (-0.5 to 0.5 across the ribbon) at `u` (0 to 1 along
* it). The ribbon turns over where `twist` crosses zero; that point and the
* ribbon's curve both slide slowly with time, so the lines keep flowing.
*/
function lineY(s: number, u: number, layer: Layer, frame: Frame, shape: Shape, band: number) {
const t = frame.time * layer.pace;
const x = u * frame.width;
const center =
frame.height * 0.5 +
shape.slope * (x - frame.width / 2) +
band * 0.1 * Math.sin(Math.PI * 2 * (0.75 * u + 0.1) + layer.phase + t * 0.35);
const turn = 0.22 + 0.09 * Math.sin(t * 0.21 + layer.phase);
const breathe = 0.3 * Math.sin(t * 0.5 + s * 4 + layer.phase);
const twist = Math.cos(Math.PI * (u - turn) + s * (0.6 + breathe) + layer.phase);
return center + s * shape.spread * band * twist;
}
/** Push a point away from the cursor, vertically, with a soft falloff. */
function part(x: number, y: number, frame: Frame, strength: number) {
const { pointer } = frame;
if (pointer.amount < 0.001) return y;
const dx = x - pointer.x;
const dy = y - pointer.y;
const falloff = Math.exp(-(dx * dx + dy * dy) / (PART_RADIUS * PART_RADIUS));
// A soft sign, so lines right under the cursor split smoothly, not snap.
const side = dy / (Math.abs(dy) + 24);
return y + side * falloff * PART_PUSH * strength * pointer.amount;
}
function drawLines(ctx: CanvasRenderingContext2D, frame: Frame, shape: Shape, color: string, front: string) {
const { width, height } = frame;
ctx.clearRect(0, 0, width, height);
ctx.lineCap = "round";
ctx.lineJoin = "round";
// On tall, narrow screens a full-height ribbon turns too steeply to read,
// so its height is capped relative to the width.
const band = Math.min(height, width * 1.1);
const perLayer = Math.max(1, Math.round(shape.count / LAYERS.length));
const xs = new Float32Array(SAMPLES + 1);
const ys = new Float32Array(SAMPLES + 1);
LAYERS.forEach((layer, layerIndex) => {
ctx.lineWidth = layer.width;
ctx.strokeStyle = layerIndex === LAYERS.length - 1 ? front : color;
for (let i = 0; i < perLayer; i++) {
const drawn = frame.drawn[layerIndex * perLayer + i] ?? 1;
if (drawn <= 0) continue;
const s = perLayer === 1 ? 0 : i / (perLayer - 1) - 0.5;
const last = Math.max(1, Math.ceil(SAMPLES * drawn));
for (let k = 0; k <= last; k++) {
const u = -OVERSCAN + (k / SAMPLES) * (1 + OVERSCAN * 2);
const x = u * width;
const y = lineY(s, u, layer, frame, shape, band);
xs[k] = x;
ys[k] = shape.interactive ? part(x, y, frame, layer.part) : y;
}
// The ribbon's edges fade, its middle carries the weight.
ctx.globalAlpha = layer.opacity * (0.45 + 0.55 * (1 - Math.abs(s) * 2));
ctx.beginPath();
ctx.moveTo(xs[0], ys[0]);
// Curves through the midpoints keep the line smooth at any sampling.
for (let k = 1; k < last; k++) {
const mx = (xs[k] + xs[k + 1]) / 2;
const my = (ys[k] + ys[k + 1]) / 2;
ctx.quadraticCurveTo(xs[k], ys[k], mx, my);
}
ctx.lineTo(xs[last], ys[last]);
ctx.stroke();
}
});
ctx.globalAlpha = 1;
}
const EASE_OUT = (t: number) => 1 - (1 - t) ** 3;
/**
* A calm ribbon of fine lines that keeps flowing behind a section, drawn on a canvas in one
* or two colours. Move the cursor through it and the lines part around you. It pauses when
* scrolled away or in a hidden tab, and holds still for reduced motion.
*/
export function RibbonLines({
className = "",
style,
children,
count = 42,
spread = 1,
angle = -8,
speed = 1,
interactive = true,
color = "#1ABCFE",
frontColor,
dark = false,
}: RibbonLinesProps) {
const rootRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const frontRef = useRef<HTMLSpanElement>(null);
useEffect(() => {
const root = rootRef.current;
const canvas = canvasRef.current;
const ctx = canvas?.getContext("2d");
if (!(root && canvas && ctx)) return;
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const shape: Shape = {
count,
spread,
slope: Math.tan((angle * Math.PI) / 180),
interactive: interactive && !reduceMotion,
};
const perLayer = Math.max(1, Math.round(count / LAYERS.length));
const total = perLayer * LAYERS.length;
const frame: Frame = {
width: 0,
height: 0,
// Start mid-flow, so the first frame isn't the same every visit.
time: 40,
drawn: new Array(total).fill(reduceMotion ? 1 : 0),
pointer: { x: 0, y: 0, amount: 0, on: false },
};
// Colours are read back from the page, so any CSS colour (or currentColor) works.
const readColors = () => {
const back = getComputedStyle(canvas).color;
const front = frontRef.current ? getComputedStyle(frontRef.current).color : back;
return { back, front };
};
let colors = readColors();
let start = 0;
let last = 0;
let raf = 0;
let visible = true;
const paint = () => drawLines(ctx, frame, shape, colors.back, colors.front);
const resize = () => {
const rect = canvas.getBoundingClientRect();
const dpr = Math.min(window.devicePixelRatio || 1, 2);
frame.width = rect.width;
frame.height = rect.height;
canvas.width = Math.round(rect.width * dpr);
canvas.height = Math.round(rect.height * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
paint();
};
const loop = (now: number) => {
raf = 0;
if (!start) {
start = now;
last = now;
}
const dt = Math.min((now - last) / 1000, 0.05);
last = now;
frame.time += dt * speed;
// The entrance draws each line on once, left to right, staggered.
const elapsed = now - start;
for (let i = 0; i < frame.drawn.length; i++) {
if (frame.drawn[i] < 1) {
const local = (elapsed - (i % perLayer) * DRAW_STAGGER_MS) / DRAW_MS;
frame.drawn[i] = EASE_OUT(Math.min(Math.max(local, 0), 1));
}
}
const { pointer } = frame;
pointer.amount += ((pointer.on ? 1 : 0) - pointer.amount) * 0.08;
paint();
const settling = frame.drawn.some((d) => d < 1) || (pointer.amount > 0.001 && !pointer.on) || pointer.on;
if (visible && (speed > 0 || settling)) raf = requestAnimationFrame(loop);
};
const play = () => {
if (!raf && visible && !reduceMotion) {
last = performance.now();
raf = requestAnimationFrame(loop);
}
};
resize();
canvas.style.opacity = "1";
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(canvas);
// A tab coming back must not wake a background that's scrolled away.
let onScreen = true;
const intersection = new IntersectionObserver(([entry]) => {
onScreen = entry.isIntersecting;
visible = onScreen && !document.hidden;
if (visible) play();
});
intersection.observe(root);
const onVisibility = () => {
visible = onScreen && !document.hidden;
if (visible) play();
};
document.addEventListener("visibilitychange", onVisibility);
// Follow a change of colour, read from the page itself.
const colorTimer = window.setInterval(() => {
if (!visible) return;
const next = readColors();
if (next.back !== colors.back || next.front !== colors.front) {
colors = next;
paint();
}
}, 500);
const onMove = (event: PointerEvent) => {
if (event.pointerType !== "mouse" || !shape.interactive) return;
const rect = canvas.getBoundingClientRect();
frame.pointer.x = event.clientX - rect.left;
frame.pointer.y = event.clientY - rect.top;
frame.pointer.on = true;
play();
};
const onLeave = () => {
frame.pointer.on = false;
play();
};
root.addEventListener("pointermove", onMove);
root.addEventListener("pointerleave", onLeave);
play();
return () => {
cancelAnimationFrame(raf);
resizeObserver.disconnect();
intersection.disconnect();
document.removeEventListener("visibilitychange", onVisibility);
window.clearInterval(colorTimer);
root.removeEventListener("pointermove", onMove);
root.removeEventListener("pointerleave", onLeave);
};
}, [count, spread, angle, speed, interactive]);
return (
<div ref={rootRef} className={`${st.root} ${dark ? st.dark : ""} ${className}`} style={style}>
{/* Faded at the top and bottom, and quieter behind centred content. */}
<div aria-hidden="true" className={st.fade}>
<canvas ref={canvasRef} className={st.canvas} style={{ color }} />
<span ref={frontRef} className={st.colorProbe} style={{ color: frontColor ?? color }} />
</div>
{children}
</div>
);
}
/* Flowing lines: a canvas behind the content, faded at the top and bottom and quieter in the middle. */
.root {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
min-height: 560px;
overflow: hidden;
background: #ffffff;
color: #1e1e1e;
}
.dark {
background: #1e1e1e;
color: #ffffff;
}
.fade {
position: absolute;
inset: 0;
pointer-events: none;
-webkit-mask-image: linear-gradient(to bottom, transparent, #000 15%, #000 85%, transparent),
radial-gradient(ellipse 40% 32% at 50% 50%, rgba(0, 0, 0, 0.3), #000);
mask-image: linear-gradient(to bottom, transparent, #000 15%, #000 85%, transparent),
radial-gradient(ellipse 40% 32% at 50% 50%, rgba(0, 0, 0, 0.3), #000);
-webkit-mask-composite: source-in;
mask-composite: intersect;
}
.canvas {
display: block;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 500ms ease-out;
}
/* Holds the front layer's colour so the canvas can read it back; never seen. */
.colorProbe {
position: absolute;
width: 0;
height: 0;
overflow: hidden;
}