DocumentationImageText

ImageText

A photograph moves through stationary, selectable text.

A little curiosity. A fresh perspective. A world of color, waiting between the lines.

Pass plain text through the text prop. Native attributes and events use Svelte spelling, such as onclick, and bind:element gives you the root DOM element.

Quick start

The preview shows the approved white-background composition: one unsplit heading, with no labels, spans, or playback buttons.

Add to your project

Copy the component and everything it needs into your Svelte 5 project.

RecommendedUse the shadcn-svelte CLI
npx shadcn-svelte@1.8.0 add https://kida-ui.onrender.com/r/svelte/image-text.json

Run this from a project with components.json. The CLI creates all required files and installs the declared runtime dependencies. New to shadcn? Follow theinstallation guide first.

Files land in src/lib/components/ui/kida by default. SvelteKit 3 projects import them through #lib; SvelteKit 2 and Vite projects use $lib, as in the examples here.

View registry JSON
Copy manually6 files

1. Create the source files

Keep this directory structure so the component's relative imports continue to work.

src/lib/components/ui/kida/image-text.svelte
<script lang="ts">
import './image-text.css'
import { type ImageTextControls, imageText, imageTextStyle } from './image-text.motion.js'
import { untrack } from 'svelte'
import type { ImageTextProps } from './image-text.types.js'

let {
  text,
  as = 'h2',
  image,
  position,
  duration,
  zoom,
  paused = false,
  element = $bindable(null),
  style,
  ...rest
}: ImageTextProps = $props()

let controls: ImageTextControls | null = null
const root = $derived(element)
const restartKey = $derived(JSON.stringify([text, duration, image, zoom]))

const rootStyle = $derived.by(() => {
  const authored = style
  const variables = imageTextStyle({ image, position, duration })
  const measured = untrack(() => element?.style.getPropertyValue('--kida-image-text-size'))
  if (measured) variables['--kida-image-text-size'] = measured
  return [...Object.entries(variables).map(([key, value]) => `${key}: ${value}`), authored]
    .filter(Boolean)
    .join('; ')
})

const attributes = $derived({
  ...rest,
  style: rootStyle,
  'data-kida-image-text': '',
  'data-image': 'loading',
  'data-state': 'pending',
  'data-suspended': 'true',
  'data-paused': String(paused),
})

$effect(() => {
  const node = root
  void restartKey
  if (!node) return
  const created = untrack(() => imageText(node, { image, position, duration, zoom, paused }))
  controls = created
  return () => {
    created.destroy()
    if (controls === created) controls = null
  }
})

$effect(() => {
  const value = paused
  untrack(() => controls?.setPaused(value))
})
</script>

{#if as === 'h1'}<h1 {...attributes} bind:this={element}>{text}</h1>
{:else if as === 'h3'}<h3 {...attributes} bind:this={element}>{text}</h3>
{:else if as === 'h4'}<h4 {...attributes} bind:this={element}>{text}</h4>
{:else if as === 'h5'}<h5 {...attributes} bind:this={element}>{text}</h5>
{:else if as === 'h6'}<h6 {...attributes} bind:this={element}>{text}</h6>
{:else if as === 'p'}<p {...attributes} bind:this={element}>{text}</p>
{:else}<h2 {...attributes} bind:this={element}>{text}</h2>
{/if}
src/lib/components/ui/kida/image-text.types.ts
import type { ImageTextOptions } from './image-text.motion.js';

import type { HTMLAttributes } from 'svelte/elements';

type TextAttributes<T extends EventTarget> = Omit<HTMLAttributes<T>, 'children'>;

export interface ImageTextProps extends ImageTextOptions, TextAttributes<HTMLElement> {
    text: string;
    as?: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'p';
    element?: HTMLElement | null;
}
src/lib/components/ui/kida/image-text.motion.ts
import { prefersReducedMotion, watchReducedMotion } from './reduced-motion.motion.js'

export interface ImageTextOptions {
  /** A photo or texture supplied by the application. */
  image: string
  /** Center crop, in percentages. @default [50, 50] */
  position?: readonly [number, number]
  /** Milliseconds per complete crop cycle; zero is static. @default 9600 */
  duration?: number
  /** Image overscan, clamped to 1–4. @default 1.28 */
  zoom?: number
  /** Freeze the current frame without restarting the cycle. @default false */
  paused?: boolean
}

export interface ImageTextControls {
  setPaused(paused: boolean): void
  destroy(): void
}

const finite = (value: number | undefined, fallback: number) =>
  value !== undefined && Number.isFinite(value) ? value : fallback
const percent = (value: number) => Math.min(100, Math.max(0, value))

/** Deterministic styles for SSR and the shared background-position keyframes. */
export function imageTextStyle({
  image,
  position,
  duration,
}: ImageTextOptions): Record<string, string> {
  const x = percent(finite(position?.[0], 50))
  const y = percent(finite(position?.[1], 50))
  const crop = (dx: number, dy: number) => `${percent(x + dx)}% ${percent(y + dy)}%`
  return {
    '--kida-image-text-image': image.trim() ? `url(${JSON.stringify(image)})` : 'none',
    '--kida-image-text-position': crop(0, 0),
    '--kida-image-text-crop-one': crop(30, -16),
    '--kida-image-text-crop-two': crop(-26, 18),
    '--kida-image-text-crop-three': crop(18, -8),
    ...(duration === undefined
      ? {}
      : { '--kida-image-text-duration': `${Math.max(0, finite(duration, 9600))}ms` }),
  }
}

/** A decoded photograph moves beneath one unsplit text element. No per-frame JS work. */
export function imageText(root: HTMLElement, options: ImageTextOptions): ImageTextControls {
  let disposed = false
  let decoded = false
  let visible = false
  let paused = options.paused ?? false
  let reduced = prefersReducedMotion()
  const duration = Math.max(0, finite(options.duration, 9600))
  const zoom = Math.min(4, Math.max(1, finite(options.zoom, 1.28)))
  const photo = new Image()

  root.dataset.image = 'loading'
  root.dataset.state = 'pending'
  root.dataset.suspended = 'true'
  root.dataset.paused = String(paused)

  const measure = () => {
    if (disposed || !decoded) return
    // Decode, font reflow and resize are the only geometry reads; animation just repaints.
    const scale =
      Math.max(root.clientWidth / photo.naturalWidth, root.clientHeight / photo.naturalHeight) *
      zoom
    root.style.setProperty(
      '--kida-image-text-size',
      `${Math.ceil(photo.naturalWidth * scale)}px ${Math.ceil(photo.naturalHeight * scale)}px`,
    )
  }
  const update = () => {
    if (disposed || !decoded) return
    if (reduced || duration === 0 || !root.textContent?.trim()) {
      root.dataset.state = 'settled'
    } else if (visible && !document.hidden && !paused) {
      root.dataset.state = 'moving'
    }
    root.dataset.suspended = String(
      root.dataset.state !== 'moving' || paused || !visible || document.hidden,
    )
  }
  const fail = () => {
    if (disposed) return
    root.dataset.image = 'error'
    root.dataset.state = 'fallback'
  }
  const intersection = new IntersectionObserver(([entry]) => {
    visible = entry?.isIntersecting ?? false
    update()
  })
  const resize = new ResizeObserver(measure)
  const unwatch = watchReducedMotion((value) => {
    reduced = value
    update()
  })

  photo.onload = async () => {
    try {
      await photo.decode()
      if (disposed) return
      decoded = true
      measure()
      root.dataset.image = 'ready'
      update()
    } catch {
      fail()
    }
  }
  photo.onerror = fail
  intersection.observe(root)
  resize.observe(root)
  document.addEventListener('visibilitychange', update)
  if (options.image.trim()) photo.src = options.image
  else fail()

  return {
    setPaused(value) {
      if (disposed) return
      paused = value
      root.dataset.paused = String(value)
      update()
    },
    destroy() {
      disposed = true
      photo.onload = null
      photo.onerror = null
      photo.removeAttribute('src')
      intersection.disconnect()
      resize.disconnect()
      unwatch()
      document.removeEventListener('visibilitychange', update)
      root.dataset.state = 'pending'
      root.dataset.image = 'loading'
      root.dataset.suspended = 'true'
      root.style.removeProperty('--kida-image-text-size')
    },
  }
}
src/lib/components/ui/kida/reduced-motion.motion.ts
const QUERY = '(prefers-reduced-motion: reduce)'

/**
 * Whether the user has asked for reduced motion.
 *
 * SSR-safe: returns `false` when there is no `window`, matching the CSS default
 * (the `prefers-reduced-motion` media query in `@kida-ui/styles` is the real guard;
 * this is for the JS-driven paths that CSS cannot express).
 */
export function prefersReducedMotion(): boolean {
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false
  return window.matchMedia(QUERY).matches
}

/**
 * Subscribe to changes of the reduced-motion preference.
 * Returns an unsubscribe function. No-op (and immediately unsubscribable) on the server.
 */
export function watchReducedMotion(onChange: (reduced: boolean) => void): () => void {
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return () => {}

  const list = window.matchMedia(QUERY)
  const handler = (event: MediaQueryListEvent) => onChange(event.matches)
  list.addEventListener('change', handler)
  return () => list.removeEventListener('change', handler)
}
src/lib/components/ui/kida/image-text.css
@import './tokens.css';

[data-kida-image-text] {
  margin: 0;
  color: var(--kida-image-text-ink, var(--kida-ink, #211c24));
  font-size: var(--kida-image-text-font-size, clamp(2.5rem, 6vw, 7.375rem));
  font-weight: var(--kida-image-text-weight, 520);
  line-height: var(--kida-image-text-leading, 1.06);
  letter-spacing: var(--kida-image-text-tracking, -0.065em);
  overflow-wrap: anywhere;
  text-wrap: pretty;
}

@supports ((background-clip: text) or (-webkit-background-clip: text)) {
  [data-kida-image-text][data-image="ready"] {
    background-color: var(--kida-image-text-ink, var(--kida-ink, #211c24));
    background-image:
      linear-gradient(
        var(--kida-image-text-tint, #3c092b8c),
        var(--kida-image-text-tint, #3c092b8c)
      ),
      var(--kida-image-text-image);
    background-size:
      100% 100%,
      var(--kida-image-text-size, cover);
    background-repeat: no-repeat;
    background-position: var(--kida-image-text-position, 50% 50%);
    background-clip: text;
    -webkit-background-clip: text;
    color: transparent;
    -webkit-text-fill-color: transparent;
  }

  [data-kida-image-text][data-image="ready"][data-state="moving"] {
    animation: kida-image-text-drift
      var(--kida-image-text-duration, calc(var(--kida-duration-xl, 800ms) * 12))
      var(--kida-ease-in-out, cubic-bezier(0.65, 0, 0.35, 1)) infinite both;
  }

  [data-kida-image-text][data-image="ready"][data-suspended="true"],
  [data-kida-image-text][data-image="ready"][data-paused="true"] {
    animation-play-state: paused;
  }
}

@keyframes kida-image-text-drift {
  0%,
  100% {
    background-position: var(--kida-image-text-position, 50% 50%);
  }
  25% {
    background-position: var(--kida-image-text-crop-one, 80% 34%);
  }
  50% {
    background-position: var(--kida-image-text-crop-two, 24% 68%);
  }
  75% {
    background-position: var(--kida-image-text-crop-three, 68% 42%);
  }
}

[data-kida-image-text]::selection {
  color: var(--kida-image-text-ink, var(--kida-ink, #211c24));
  -webkit-text-fill-color: var(--kida-image-text-ink, var(--kida-ink, #211c24));
  background: var(--kida-image-text-selection, #f4cf63);
}

@media (prefers-reduced-motion: reduce) {
  [data-kida-image-text][data-image="ready"][data-state="moving"] {
    animation: none;
  }
}

@media (forced-colors: active) {
  [data-kida-image-text][data-image="ready"] {
    background: none;
    color: CanvasText;
    -webkit-text-fill-color: CanvasText;
  }
}

@media print {
  [data-kida-image-text][data-image="ready"] {
    background: none;
    color: #211c24;
    -webkit-text-fill-color: #211c24;
  }
}

@media (forced-colors: active), print {
  [data-kida-image-text][data-image="ready"][data-state] {
    animation: none;
  }
}
src/lib/components/ui/kida/tokens.css
/*
 * Kida UI — motion tokens.
 * Plain CSS custom properties (ADR D7). No preprocessor, no Tailwind, no build step.
 */

:root {
  /* Durations */
  --kida-duration-xs: 100ms;
  --kida-duration-sm: 150ms;
  --kida-duration-md: 300ms;
  --kida-duration-lg: 500ms;
  --kida-duration-xl: 800ms;

  /* Easings */
  --kida-ease-out: cubic-bezier(0.16, 1, 0.3, 1);
  --kida-ease-in: cubic-bezier(0.7, 0, 0.84, 0);
  --kida-ease-in-out: cubic-bezier(0.65, 0, 0.35, 1);
  --kida-ease-spring: linear(0, 0.5, 0.9, 1.02, 1);

  /* Travel distances used by the enter/exit keyframes */
  --kida-distance-sm: 4px;
  --kida-distance-md: 8px;
  --kida-distance-lg: 16px;

  /* Stagger step between siblings */
  --kida-stagger: 60ms;
}

/*
 * The shared reduced-motion guard for CSS-driven animation in the library.
 * Durations collapse to ~0 by default. Components whose presence lifecycle cannot safely observe
 * a 1ms animation, such as Collapse, disable it explicitly and complete presence in their adapter.
 */
@media (prefers-reduced-motion: reduce) {
  :root {
    --kida-duration-xs: 1ms;
    --kida-duration-sm: 1ms;
    --kida-duration-md: 1ms;
    --kida-duration-lg: 1ms;
    --kida-duration-xl: 1ms;
    --kida-distance-sm: 0px;
    --kida-distance-md: 0px;
    --kida-distance-lg: 0px;
    --kida-stagger: 0ms;
  }
}
<script lang="ts">
import ImageText from '$lib/components/ui/kida/image-text.svelte'
</script>

<ImageText
  image="/photos/flowers.webp"
  text="A little curiosity. A fresh perspective. A world of color, waiting between the lines."
/>

Supply a photograph you own or are licensed to use. The quick start’s /photos/flowers.webp is an application-owned file, not an image bundled with the component.

Customization

Configure the image, center crop, duration, zoom, and playback in code. The photograph follows a smooth four-crop path and returns to its starting position every 9.6 seconds. The letters stay in place. No controls or alternate compositions are included in the website preview.

Use class and style for typography. CSS custom properties adjust the photo tint, selection color, and intermediate crops. Replacing an image or tint requires reviewing contrast throughout its movement. For a custom dark surface, use a lighter tint and fallback ink.

API

Props

Prop Type Default Description
text string required One readable, selectable text sequence.
image string required Photo or texture URL.
position readonly [number, number] [50, 50] Center crop in percentages, clamped to 0–100.
duration number 9600 Milliseconds per complete cycle; 0 is static.
zoom number 1.28 Overscan, clamped to 1–4, to maintain coverage while moving.
paused boolean false Pause on the current frame; resume without restarting.
as heading tag or 'p' 'h2' Semantic root element.

The root accepts safe native attributes, event handlers, class, and style, and bind:element reads it. Changing the text, image, duration, or zoom resets the controller. Changing an equivalent crop tuple, native attribute, or paused value does not reload the image.

CSS custom properties

Property Default Description
--kida-image-text-tint #3c092b8c Translucent plum over the photograph for contrast.
--kida-image-text-ink --kida-ink or #211c24 Solid loading/error fallback and selection ink.
--kida-image-text-selection #f4cf63 Text selection background.
--kida-image-text-font-size clamp(2.5rem, 6vw, 7.375rem) Display text size.
--kida-image-text-weight 520 Font weight.
--kida-image-text-leading 1.06 Line height.
--kida-image-text-tracking -0.065em Letter spacing.
--kida-image-text-duration 12 XL motion durations Cycle duration when the prop is omitted.
--kida-image-text-crop-one center + [30, -16] First intermediate crop, clamped to 0–100.
--kida-image-text-crop-two center + [-26, 18] Second intermediate crop.
--kida-image-text-crop-three center + [18, -8] Third intermediate crop.

Accessibility and input behavior

The component renders a single heading or paragraph with a text node. There are no split spans, duplicated accessible copies, image elements, or generated buttons. Selection and copy use the authored text, and the photograph is decorative.

Reduced motion shows the center crop without animation. Solid text remains available before hydration, during loading, after an image failure, and when text clipping is unavailable. Forced colors and print use solid text. Each instance waits for image decode and viewport entry; motion pauses offscreen or while the document is hidden. Resizing and delayed fonts remeasure the photo without a per-frame layout loop.

The component supplies controlled paused playback so applications can connect their own accessible playback controls when appropriate. This requested text-only preview has no such controls and respects the operating system’s reduced-motion preference.

Troubleshooting

The photograph is cropped across the complete text block, rather than repeated per letter. Use broad color areas and serve an image close to the displayed size. The animation changes CSS background position, which repaints the text area; avoid many large, simultaneously moving instances. It has no per-frame JavaScript or Svelte updates. Chromium checks cover motion and hydration for the Svelte adapter; manual screen-reader checks are recommended.

The preview photograph is by Anthony Melone, used under the Unsplash License. Its existing asset record is in apps/docs/public/demo/image-text/README.md. The visual idea is inspired by Butter; no Butter assets or implementation are included.