Taster

진단부품톤 고르기
부품 갤러리 / Mesh drift

Mesh drift

Motion effect and particles

A GPU or canvas point cloud in neutral tones that forms shapes slowly, or thin noise-driven lines on a calm surface, replacing purple orbs and aurora blobs.

내 사이트에서 가져오기

색을 고르면 아래 부품이 그 색으로 바뀝니다.

실제로 돌아가는 부품입니다. 눌러 보고 입력해 보세요.

내 앱에 넣기

  1. 아직 npm 패키지가 없어서 Taster 리포를 받아 그 안의 명령을 씁니다. 내 앱 폴더가 들어 있는 폴더에서 한 번만 받습니다.

    git clone https://github.com/makim-414/taster.git && npm ci --prefix taster/packages/engine
  2. 내 앱 폴더에서 이 부품을 넣습니다. 부품 파일과 토큰 파일이 src/components/taster 에 들어갑니다.

    node ../taster/packages/engine/cli.mjs add motion/mesh-drift --from https://taster-six.vercel.app --dir src/components/taster
  3. 부품은 Tailwind 클래스로 그리고, Taster 프리셋이 그 클래스를 토큰에 연결합니다. Tailwind CSS 를 설치하고, tokens.css 를 앱 루트에서 한 번 불러온 뒤, 앱 루트에 이 설정을 둡니다. 프리셋이 없으면 빌드는 되어도 부품이 스타일 없이 나옵니다.

    // tailwind.config.cjs
    module.exports = {
      presets: [require('./src/components/taster/tailwind-preset.cjs')],
      content: ['./index.html', './src/**/*.{ts,tsx}'],
    };

    Tailwind v3 는 이 파일을 그대로 읽습니다. v4 는 Tailwind 를 불러오는 src/ 의 스타일시트 맨 위에 이 두 줄을 넣습니다.

    @import "tailwindcss";
    @config "../tailwind.config.cjs";

    tokens.css 는 :root 에 --bg, --text, --border, --accent 를 정의합니다. 내 앱의 스타일시트가 같은 이름을 뒤에서 다시 정의하면 그쪽 색이 이깁니다. 새 Vite 앱의 스타터 CSS 처럼 그런 변수가 있으면 지우거나 이름을 바꾸세요.

언제 쓰나요

  • Ambient backgroundA GPU or canvas point cloud in neutral tones that forms shapes slowly, or thin noise-driven lines on a calm surface, replacing purple orbs and aurora blobs.

대신 없애 주는 AI 티

  • Aurora or mesh blob background (BG-01)
  • Purple gradient (COL-01)
  • Near-black background with a neon glow (COL-03)

정보

설치할 패키지
tailwindcss
라이선스
MIT
출처
DARK MONO by thom (21st.dev @admin_5eaa986a), generated with the 21st.dev Shader Builder, MIT as listed, https://21st.dev/@admin_5eaa986a/components/dark-mono
코드 보기
import * as React from 'react'
import { resolveColor, type Rgb } from './_color'

// Mesh drift: a slow field of soft color pools on one WebGL canvas that fills its parent, with film
// grain and an optional vignette. Put it behind a short hero or a sign-in screen, never behind dense text.
// Source: "DARK MONO", generated by the 21st.dev Shader Builder ("Mesh drift") and published by
// admin_5eaa986a (https://21st.dev/@admin_5eaa986a/components/dark-mono).
// Changes: the palette is a prop with named variations (mono, the default, is built from the
// --bg and --chart-* tokens and follows a theme switch; brand mixes --bg into --brand), the cursor
// spotlight is off by default (patterns/ambient-background.md: the field does not follow the
// cursor), speed and grain are props, and reduced motion draws one still frame.
// Upstream license: MIT as stated on the 21st.dev listing (no LICENSE file published).
// Full text in THIRD_PARTY_NOTICES.md.

/** Named palettes. The first color is the base the pools float on. */
export const MESH_PALETTES = {
  /** Neutral lightness steps from the tokens. Safe on any page. */
  mono: ['var(--bg)', 'var(--chart-6)', 'var(--chart-5)', 'var(--chart-4)', 'var(--chart-3)'],
  /** --bg rising into --brand in four steps. Follows whatever brand the page sets. */
  brand: ['brand'],
  /** The original DARK MONO: near black with cold blues. */
  ink: ['#171717', '#91c5ff', '#3a81f6', '#2563ef', '#1a4eda'],
  /** Warm paper and clay, low contrast. Reads as print, not as a glow. */
  sand: ['#14110d', '#3a3127', '#6e5f4c', '#b5a48a', '#ece3d3'],
  /** Embers in a dark room. */
  ember: ['#120a08', '#5a1d10', '#b8441f', '#f08a4b', '#ffd2a8'],
  /** Moss and lichen. */
  moss: ['#0a0f0b', '#1e3a2a', '#3f6e4f', '#8fb08a', '#e2ecd5'],
  /** Slate and fog, a cool neutral. */
  fog: ['#0c0e11', '#242a31', '#47515c', '#8995a1', '#d5dbe1'],
} as const

export type MeshPalette = keyof typeof MESH_PALETTES

export interface MeshDriftProps {
  /** A named palette, or 2 to 8 CSS colors (tokens allowed), base color first. Default mono. */
  palette?: MeshPalette | string[]
  /** Time multiplier. 0 holds a still frame. Default 0.6, slower than reading speed. */
  speed?: number
  /** Film grain amount, 0 to 0.4. Default 0.18. */
  grain?: number
  /** Darkens the corners, 0 to 1. Default 0.5. */
  vignette?: number
  /** A soft light under the pointer. Default false. */
  cursor?: boolean
  /** Different arrangement of the same palette. */
  seed?: number
  className?: string
  style?: React.CSSProperties
}

const VERT = `attribute vec2 a_position;
void main() {
  gl_Position = vec4(a_position, 0.0, 1.0);
}`

const FRAG = `#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
#else
precision mediump float;
#endif

uniform vec3 u_colors[8];
// Seven packed vectors + eight colour vectors = 15 fragment uniform vectors,
// one below WebGL1's guaranteed minimum. Macros preserve the public u_* API.
uniform vec4 u_scene;      // resolution.xy, time, colour count
uniform vec4 u_shape;      // scale, intensity, paramA, warp
uniform vec4 u_surface;    // detail, contrast, brightness, saturation
uniform vec4 u_finish;     // hue, vignette, blur, grain
uniform vec4 u_transform;  // seed, rotation, drift, OKLab toggle
uniform vec4 u_space;      // offset.xy, pointer.xy
uniform vec4 u_cursor;

#define u_resolution u_scene.xy
#define u_time u_scene.z
#define u_colorCount u_scene.w
#define u_scale u_shape.x
#define u_intensity u_shape.y
#define u_paramA u_shape.z
#define u_warp u_shape.w
#define u_detail u_surface.x
#define u_contrast u_surface.y
#define u_brightness u_surface.z
#define u_saturation u_surface.w
#define u_hue u_finish.x
#define u_vignette u_finish.y
#define u_blur u_finish.z
#define u_grain u_finish.w
#ifdef GL_FRAGMENT_PRECISION_HIGH
#define u_seed u_transform.x
#else
#define u_seed mod(u_transform.x, 31.0)
#endif
#define u_rotate u_transform.y
#define u_drift u_transform.z
#define u_oklab u_transform.w
#define u_offset u_space.xy
#define u_mouse u_space.zw
#define u_cursorPresence u_cursor.x
#define u_cursorEffect u_cursor.y
#define u_cursorStrength u_cursor.z
#define u_cursorRadius u_cursor.w

float hash21(vec2 p) {
#ifndef GL_FRAGMENT_PRECISION_HIGH
  p = mod(p, 31.0);
#endif
  p = fract(p * vec2(234.34, 435.345));
  p += dot(p, p + 34.23);
  return fract(p.x * p.y);
}

// Even white noise for film grain (Dave Hoskins hash12).
float grainHash(vec2 p) {
  vec3 p3 = fract(vec3(p.xyx) * 0.1031);
  p3 += dot(p3, p3.yzx + 33.33);
  return fract((p3.x + p3.y) * p3.z);
}

float noise(vec2 p) {
  vec2 i = floor(p);
  vec2 f = fract(p);
  vec2 u = f * f * (3.0 - 2.0 * f);
  return mix(
    mix(hash21(i), hash21(i + vec2(1.0, 0.0)), u.x),
    mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), u.x),
    u.y);
}

float fbm(vec2 p) {
  float v = 0.0;
  float a = 0.5;
  for (int i = 0; i < 5; i++) {
    v += a * noise(p);
    p = p * 2.03 + vec2(17.0, 9.2);
    a *= 0.5;
  }
  return v;
}

vec3 hueRotate(vec3 col, float a) {
  const mat3 toYIQ = mat3(0.299, 0.596, 0.211,
                          0.587, -0.274, -0.523,
                          0.114, -0.322, 0.312);
  const mat3 toRGB = mat3(1.0, 1.0, 1.0,
                          0.956, -0.272, -1.106,
                          0.621, -0.647, 1.703);
  vec3 yiq = toYIQ * col;
  float ca = cos(a), sa = sin(a);
  yiq = vec3(yiq.x, yiq.y * ca - yiq.z * sa, yiq.y * sa + yiq.z * ca);
  return toRGB * yiq;
}

vec3 shade(vec2 uv, vec2 p, float t) {
  vec3 acc = u_colors[0] * 0.15;
  float total = 0.15;
  for (int i = 0; i < 8; i++) {
    if (float(i) >= u_colorCount) break;
    float fi = float(i);
    vec2 c = vec2(
      sin(t * (0.21 + fi * 0.071) + fi * 2.4 + u_seed),
      cos(t * (0.17 + fi * 0.093) + fi * 1.7)) * (0.45 + u_intensity * 0.35);
    float w = exp(-dot(p - c, p - c) * 6.0);
    acc += u_colors[i] * w;
    total += w;
  }
  return acc / total;
}

void main() {
  vec2 uv = gl_FragCoord.xy / u_resolution.xy;
  vec2 screenUv = uv;
  vec2 p = (gl_FragCoord.xy - 0.5 * u_resolution.xy)
    / min(u_resolution.x, u_resolution.y);
  float cursorMask = 0.0;

  if (u_cursorPresence > 0.001) {
    vec2 cursor = (0.5 * u_mouse * u_resolution.xy)
      / min(u_resolution.x, u_resolution.y);
    float cursorDistance = length(p - cursor);
    cursorMask = u_cursorPresence
      * (1.0 - smoothstep(0.0, u_cursorRadius, cursorDistance));
  }

  uv = p * min(u_resolution.x, u_resolution.y) / u_resolution.xy + 0.5;
  p *= u_scale;
  if (abs(u_rotate) > 0.0001) {
    float cr = cos(u_rotate), sr = sin(u_rotate);
    p = mat2(cr, -sr, sr, cr) * p;
  }
  p += u_offset;
  if (u_drift > 0.0001)
    p += u_drift * vec2(sin(u_time * 0.31), cos(u_time * 0.23));
  if (u_warp > 0.0) {
    p += u_warp * (vec2(
      fbm(p * u_detail + u_seed),
      fbm(p * u_detail + vec2(5.2, 1.3))) - 0.5);
  }
  vec3 col = shade(uv, p, u_time);
  if (abs(u_contrast - 1.0) > 0.0001)
    col = (col - 0.5) * u_contrast + 0.5;
  if (abs(u_saturation - 1.0) > 0.0001) {
    float luma = dot(col, vec3(0.299, 0.587, 0.114));
    col = mix(vec3(luma), col, u_saturation);
  }
  if (abs(u_hue) > 0.0001)
    col = hueRotate(col, u_hue);
  if (abs(u_brightness) > 0.0001)
    col += u_brightness;
  if (u_vignette > 0.0001) {
    float vd = length(screenUv - 0.5) * 1.41421356;
    col *= 1.0 - u_vignette * smoothstep(0.35, 1.0, vd);
  }
  if (u_cursorPresence > 0.001)
    col += (vec3(0.18) + col * 0.12) * cursorMask * u_cursorStrength;
  if (u_grain > 0.0001)
    col += (grainHash(
      gl_FragCoord.xy + vec2(u_seed * 17.0, u_seed * 31.0)) - 0.5) * u_grain;
  gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
}
`

// Shape and finish of the original recipe. Contrast and saturation are tuned for the ink palette and
// pulled toward neutral for the others, so mono stays gray.
const RECIPE = {
  scale: 1.26,
  intensity: 0.35,
  paramA: 0.28,
  warp: 0,
  detail: 1.824,
  brightness: -0.02,
  hue: 0,
  blur: 0,
  rotate: 0,
  offsetX: -0.05,
  offsetY: 0,
  drift: 0.06,
  cursorStrength: 0.5,
  cursorRadius: 0.8,
}

const mixRgb = (a: Rgb, b: Rgb, t: number): Rgb => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]

function paletteColors(palette: MeshPalette | string[], el: Element): Rgb[] {
  const list = typeof palette === 'string' ? MESH_PALETTES[palette] ?? MESH_PALETTES.mono : palette
  if (list.length === 1 && list[0] === 'brand') {
    const bg = resolveColor('var(--bg)', el)
    const brand = resolveColor('var(--brand)', el, [1, 1, 1])
    return [0, 0.25, 0.5, 0.75, 1].map((t) => mixRgb(bg, brand, t * 0.85))
  }
  const out = list.slice(0, 8).map((c) => resolveColor(c, el))
  while (out.length < 2) out.push(out[0] ?? [0, 0, 0])
  return out
}

const pendingContextReleases = new WeakMap<HTMLCanvasElement, number>()

export function MeshDrift({
  palette = 'mono',
  speed = 0.6,
  grain = 0.18,
  vignette = 0.5,
  cursor = false,
  seed = 1,
  className,
  style,
}: MeshDriftProps) {
  const canvasRef = React.useRef<HTMLCanvasElement>(null)
  const paletteKey = typeof palette === 'string' ? palette : JSON.stringify(palette)
  const live = React.useRef({ palette, speed, grain, vignette, cursor, seed })
  live.current = { palette, speed, grain, vignette, cursor, seed }
  const pushRef = React.useRef<() => void>(() => {})

  React.useEffect(() => {
    const found = canvasRef.current
    if (!found) return
    const canvas: HTMLCanvasElement = found
    const pendingRelease = pendingContextReleases.get(canvas)
    if (pendingRelease !== undefined) window.clearTimeout(pendingRelease)
    pendingContextReleases.delete(canvas)
    const ctx = canvas.getContext('webgl', { antialias: false })
    if (!ctx) return
    const gl: WebGLRenderingContext = ctx

    const compile = (type: number, src: string) => {
      const s = gl.createShader(type)!
      gl.shaderSource(s, src)
      gl.compileShader(s)
      return s
    }
    const program = gl.createProgram()!
    const vertexShader = compile(gl.VERTEX_SHADER, VERT)
    const fragmentShader = compile(gl.FRAGMENT_SHADER, FRAG)
    gl.attachShader(program, vertexShader)
    gl.attachShader(program, fragmentShader)
    gl.linkProgram(program)
    gl.deleteShader(vertexShader)
    gl.deleteShader(fragmentShader)
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) return
    gl.useProgram(program)

    const buf = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, buf)
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW)
    const loc = gl.getAttribLocation(program, 'a_position')
    gl.enableVertexAttribArray(loc)
    gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0)

    const uni = {
      colors: gl.getUniformLocation(program, 'u_colors'),
      scene: gl.getUniformLocation(program, 'u_scene'),
      shape: gl.getUniformLocation(program, 'u_shape'),
      surface: gl.getUniformLocation(program, 'u_surface'),
      finish: gl.getUniformLocation(program, 'u_finish'),
      transform: gl.getUniformLocation(program, 'u_transform'),
      space: gl.getUniformLocation(program, 'u_space'),
      cursor: gl.getUniformLocation(program, 'u_cursor'),
    }

    let colorCount = 2
    // Static uniforms: palette and finish. Called again when a prop or the theme changes.
    const push = () => {
      const P = live.current
      const cols = paletteColors(P.palette, canvas)
      colorCount = cols.length
      const flat = new Float32Array(24)
      cols.forEach((c, i) => flat.set(c, i * 3))
      gl.uniform3fv(uni.colors, flat)
      const ink = P.palette === 'ink'
      gl.uniform4f(uni.shape, RECIPE.scale, RECIPE.intensity, RECIPE.paramA, RECIPE.warp)
      gl.uniform4f(uni.surface, RECIPE.detail, ink ? 1.374 : 1.15, RECIPE.brightness, ink ? 0.68 : 1)
      gl.uniform4f(uni.finish, RECIPE.hue, Math.max(0, Math.min(1, P.vignette)), RECIPE.blur, Math.max(0, Math.min(0.4, P.grain)))
      gl.uniform4f(uni.transform, P.seed, RECIPE.rotate, RECIPE.drift, 1)
      requestRender()
    }

    let targetX = 0
    let targetY = 0
    let targetPresence = 0
    let mouseX = 0
    let mouseY = 0
    let cursorPresence = 0
    let bounds = canvas.getBoundingClientRect()
    let raf = 0
    let lastNow: number | null = null
    let visible = document.visibilityState === 'visible'
    let inView = true
    let disposed = false
    let clock = 0
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches

    const resizeCanvas = () => {
      const dpr = Math.min(window.devicePixelRatio || 1, 2)
      const rawWidth = Math.max(1, Math.round(bounds.width * dpr))
      const rawHeight = Math.max(1, Math.round(bounds.height * dpr))
      const pixelScale = Math.min(1, Math.sqrt(2_000_000 / Math.max(1, rawWidth * rawHeight)))
      const width = Math.max(1, Math.round(rawWidth * pixelScale))
      const height = Math.max(1, Math.round(rawHeight * pixelScale))
      if (canvas.width !== width || canvas.height !== height) {
        canvas.width = width
        canvas.height = height
        gl.viewport(0, 0, width, height)
      }
    }

    function requestRender() {
      if (!disposed && visible && inView && raf === 0) raf = requestAnimationFrame(render)
    }

    const onPointerMove = (event: PointerEvent) => {
      if (!live.current.cursor || event.pointerType === 'touch') return
      bounds = canvas.getBoundingClientRect()
      const inside = event.clientX >= bounds.left && event.clientX <= bounds.right && event.clientY >= bounds.top && event.clientY <= bounds.bottom
      targetPresence = inside ? 1 : 0
      if (inside) {
        targetX = ((event.clientX - bounds.left) / bounds.width) * 2 - 1
        targetY = -(((event.clientY - bounds.top) / bounds.height) * 2 - 1)
        if (cursorPresence < 0.01) {
          mouseX = targetX
          mouseY = targetY
        }
      }
      requestRender()
    }
    const onPointerLeave = () => {
      targetPresence = 0
      requestRender()
    }
    const updateLayout = () => {
      bounds = canvas.getBoundingClientRect()
      resizeCanvas()
      requestRender()
    }
    window.addEventListener('pointermove', onPointerMove, { passive: true })
    document.documentElement.addEventListener('pointerleave', onPointerLeave)

    const resizeObserver = new ResizeObserver(updateLayout)
    resizeObserver.observe(canvas)
    const intersectionObserver = new IntersectionObserver(([entry]) => {
      inView = entry?.isIntersecting ?? true
      if (inView) requestRender()
      else if (raf !== 0) {
        cancelAnimationFrame(raf)
        raf = 0
        lastNow = null
      }
    })
    intersectionObserver.observe(canvas)
    const onVisibilityChange = () => {
      visible = document.visibilityState === 'visible'
      if (visible) requestRender()
      else if (raf !== 0) {
        cancelAnimationFrame(raf)
        raf = 0
        lastNow = null
      }
    }
    document.addEventListener('visibilitychange', onVisibilityChange)
    const themeWatch = new MutationObserver(push)
    themeWatch.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] })

    function render(now: number) {
      raf = 0
      if (disposed || !visible || !inView) return
      const P = live.current
      const dt = lastNow === null ? 0 : Math.min((now - lastNow) / 1000, 0.1)
      lastNow = now
      const timeScale = reduced ? 0 : P.speed
      clock += dt * timeScale
      const follow = 1 - Math.exp(-12 * dt)
      mouseX += (targetX - mouseX) * follow
      mouseY += (targetY - mouseY) * follow
      cursorPresence += (targetPresence - cursorPresence) * follow
      resizeCanvas()
      gl.uniform4f(uni.scene, canvas.width, canvas.height, clock + 4, colorCount)
      gl.uniform4f(uni.space, RECIPE.offsetX, RECIPE.offsetY, mouseX, mouseY)
      gl.uniform4f(uni.cursor, P.cursor ? cursorPresence : 0, 4, RECIPE.cursorStrength, RECIPE.cursorRadius)
      gl.drawArrays(gl.TRIANGLES, 0, 3)
      const settling =
        Math.abs(targetX - mouseX) > 0.001 || Math.abs(targetY - mouseY) > 0.001 || Math.abs(targetPresence - cursorPresence) > 0.001
      if (Math.abs(timeScale) > 0.0001 || settling) requestRender()
      else lastNow = null
    }

    pushRef.current = push
    push()
    return () => {
      disposed = true
      pushRef.current = () => {}
      cancelAnimationFrame(raf)
      resizeObserver.disconnect()
      intersectionObserver.disconnect()
      themeWatch.disconnect()
      document.removeEventListener('visibilitychange', onVisibilityChange)
      window.removeEventListener('pointermove', onPointerMove)
      document.documentElement.removeEventListener('pointerleave', onPointerLeave)
      gl.deleteBuffer(buf)
      gl.deleteProgram(program)
      const releaseTimer = window.setTimeout(() => {
        if (pendingContextReleases.get(canvas) !== releaseTimer) return
        pendingContextReleases.delete(canvas)
        gl.getExtension('WEBGL_lose_context')?.loseContext()
        canvas.width = 1
        canvas.height = 1
      }, 0)
      pendingContextReleases.set(canvas, releaseTimer)
    }
  }, [])

  // Palette and finish changes re-upload the static uniforms without rebuilding the program.
  React.useEffect(() => {
    pushRef.current()
  }, [paletteKey, speed, grain, vignette, cursor, seed])

  return (
    <canvas
      ref={canvasRef}
      aria-hidden="true"
      className={className}
      style={{ display: 'block', width: '100%', height: '100%', background: 'var(--bg)', pointerEvents: 'none', ...style }}
    />
  )
}