# spin

A product turns by drag through a series of photos taken around it.

A horizontal drag picks the frame from a series shot in a circle, and with rows a vertical drag picks the viewing angle. The frame follows the pointer and stops where it is let go; with inertia a flick coasts on and eases out onto a whole frame, neighbor frames cross-fading on the way so it slows without stepping. Every step shows one whole photo, so the product stays sharp at any angle; with blend neighbor frames cross-fade by the fraction instead, for sparse sets. spin turns it until the first touch, and a hint turns it a little back and forth when it first shows.

Module `media`, category 3D and product. Import `@dioramajs/media/spin`. [Source](https://github.com/MasterKurosava/diorama/blob/main/packages/media/src/spin.ts)

A rangefinder camera in 36 photos taken around it, turned by a drag, the pointer or the arrow keys.

```html title="index.html"
<img class="camera" src="/media/shop/spin/01.avif" alt="Norrvik RF-2 rangefinder camera, 360° view. Drag or use the arrow keys to turn it." width="960" height="640" data-dio="spin" data-dio-frames="/media/shop/spin/{01..36}.avif" tabindex="0" style="touch-action: pan-y" />
```

## Usage

Put it on: img (the poster).

`start()` registers `spin`, so the attribute alone puts it on an element.

```html
<img src="/spin/camera/01.webp" alt="Rangefinder camera, 360° view. Drag or use the arrow keys to turn it." data-dio="spin" data-dio-frames="/spin/camera/{01..72}.webp" data-dio-load="eager" tabindex="0" style="touch-action: pan-y" />
```

In page transitions: Fades with the page transition; a flight shows the current frame.

## Params

| Name | Attribute | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `frames` (rebuilds) | `data-dio-frames` | `string` | `''` | Frame URLs as a {01..72} range or a comma list, in turning order. |
| `atlas` (rebuilds) | `data-dio-atlas` | `string` | `''` | Atlas page URLs as a range or a list, read cell by cell. |
| `grid` (rebuilds) | `data-dio-grid` | `[number, number]` 1 to 16 | `[1, 1]` | Columns and rows of cells on an atlas page. |
| `count` (rebuilds) | `data-dio-count` | `number \| 'auto'` 1 to 360 | `'auto'` | Number of frames; auto takes all. |
| `density` (rebuilds) | `data-dio-density` | `number` 0.1 to 1 | `1` | Share of the frames to load; 0.5 takes every second. At most low 0.5. |
| `resolution` (rebuilds) | `data-dio-resolution` | `number` 256 to 4096 px | `1600` | Cap on the long side of a frame when decoding. At most low 960, medium 1280. |
| `rows` (rebuilds) | `data-dio-rows` | `number` 1 to 8 | `1` | Rows of viewing angles; frames run row after row. |
| `frame` | `data-dio-frame` | `number` 0 to 72 | `0` | Current frame in its row, fractional with blend; the effect writes it as the visitor turns it. |
| `row` | `data-dio-row` | `number` 0 to 8 | `0` | Current row of viewing angles. |
| `by` (rebuilds) | `data-dio-by` | `'drag' \| 'hover' \| 'manual'` | `'drag'` | drag turns it while pressed; hover turns it as the mouse moves over it, without a press (touch still drags); manual leaves the pointer to the page: keys, frame and spin turn it, for a product that turns by itself. |
| `sensitivity` | `data-dio-sensitivity` | `number` 0.1 to 4 | `1` | How far a drag across the full width of the box turns it, as a factor: 1 is one whole turn. |
| `spin` | `data-dio-spin` | `number` 0 to 360 deg/s | `0` | Turning by itself until the first touch, in degrees a second; 0 for none. |
| `inertia` | `data-dio-inertia` | `number` 0 to 2 s | `0` | Coast after a flick: it goes as far as the flick carries it in this time and eases out onto a whole frame over three times as long at most. 0, the default, stops on the frame where the pointer lets go. |
| `loop` | `data-dio-loop` | `boolean` | `true` | Turns full circle; off stops at the end frames. |
| `reverse` | `data-dio-reverse` | `boolean` | `false` | Reverses the order of the frames. |
| `blend` | `data-dio-blend` | `boolean` | `false` | Cross-fades neighbor frames by the fraction of the turn. Off by default: 36 or more frames turn smoothly as whole photos, and a mix of two reads as ghosting. Turn it on for sparse sets, about 24 frames or fewer, where whole frames step visibly. |
| `hint` | `data-dio-hint` | `boolean` | `true` | Turns a twelfth back and forth when it first shows. |
| `cache` | `data-dio-cache` | `number` 1 to 32 | `8` | Decoded frames kept around the current one. At most low 4, medium 6. |
| `fps` | `data-dio-fps` | `number` 1 to 60 | `30` | Frame cap while turning by itself. |

Changing a param marked rebuilds re-runs the effect setup.

### Variants

- `by`: `drag`, `hover`, `manual`
  - `drag` turns it while pressed.
  - `hover` turns it as the mouse moves over it, without a press (touch still drags).
  - `manual` leaves the pointer to the page: keys, frame and spin turn it, for a product that turns by itself.

## Inputs and frames

Reads [`delta`](/docs/api/inputs#input-delta), [`opacity`](/docs/api/inputs#opacity), [`reducedMotion`](/docs/api/inputs#input-reducedMotion), [`size`](/docs/api/inputs#size). Draws at a steady rate while it is on screen and stops when it leaves. None at rest; full rate while dragging or coasting, at most fps while turning by itself or hinting. See [how a frame is decided](/docs/concepts/frames).

## Reduced motion and touch

With reduced motion it shows a still frame: motion inputs are zero and time stands still. No spin, inertia or hint; dragging and keys still work.

Runs on every device. Dragging needs touch-action: pan-y; rows need touch-action: none.

```ts
import { start } from '@dioramajs/diorama'

start({ effects: { spin: { reducedMotion: 'off' } } })
```

## Cost and quality

Loads 5.9 KB the first time a page uses it. GPU: One or two texture reads per pixel. Memory: Compressed bytes of every frame and a window of decoded ones; an atlas keeps none decoded.

- low: Half the frames, four decoded at a time, at most 960 px.
- medium: Six decoded frames at a time, at most 1280 px.

See [the quality plugin](/docs/effects/quality).

## Recipes

### A product shot that turns

Shoot or render the product in a circle, every 5° to 10°, and name the files in turning order. The first frame is the `<img>`: it shows before the frames load, without WebGL and with reduced motion. `tabindex="0"` lets the arrow keys turn it, and `touch-action: pan-y` lets a finger turn it sideways while a vertical swipe still scrolls the page.

```html
<img
  src="/spin/camera/01.avif"
  data-dio="spin"
  data-dio-frames="/spin/camera/{01..36}.avif"
  tabindex="0"
  style="touch-action: pan-y"
/>
```

Say how to turn it in the `alt` or next to the picture. Nothing on the poster shows that it turns until the hint plays.

### Buttons for the views that sell it

The effect writes `frame` as the visitor turns the product and goes to any `frame` the page writes. Buttons for front, side and back step the handle there the short way round, and a drag carries on from wherever they leave it.

The rangefinder camera with buttons for the three-quarter, front, side and back views, which turn it there frame by frame.

```html title="index.html"
<div class="product">
  <img class="camera" src="/media/shop/spin/01.avif" alt="Norrvik RF-2 rangefinder camera, 360° view. Drag, use the arrow keys or pick a view below." width="960" height="640" data-dio="spin" data-dio-frames="/media/shop/spin/{01..36}.avif" tabindex="0" style="touch-action: pan-y" />
  <fieldset class="views">
    <legend>Views of the camera</legend>
    <button type="button" data-frame="0">Three-quarter</button>
    <button type="button" data-frame="33">Front</button>
    <button type="button" data-frame="6">Side</button>
    <button type="button" data-frame="15">Back</button>
  </fieldset>
</div>
```

```ts title="script.ts"
import { app } from '../../../../docs/diorama.ts'

// Each button turns the camera to its frame the short way round, one frame at a time.
export default function mount(example: HTMLElement): () => void {
  const camera = example.querySelector('.camera')
  const views = example.querySelector('.views')
  const count = 36
  let raf = 0
  const turnTo = (target: number) => {
    const spin = camera && app.effects.get(camera, 'spin')
    if (!spin) return
    cancelAnimationFrame(raf)
    const from = spin.params.frame
    // The shorter way round the circle.
    const delta =
      ((((target - from) % count) + count * 1.5) % count) - count / 2
    const start = performance.now()
    const duration = 120 + Math.abs(delta) * 30
    const step = (now: number) => {
      const t = Math.min(1, (now - start) / duration)
      const eased = 1 - (1 - t) ** 3
      spin.params.frame =
        ((Math.round(from + delta * eased) % count) + count) % count
      if (t < 1) raf = requestAnimationFrame(step)
    }
    raf = requestAnimationFrame(step)
  }
  const onClick = (e: Event) => {
    const button = (e.target as Element).closest<HTMLButtonElement>(
      'button[data-frame]',
    )
    if (button) turnTo(Number(button.dataset.frame))
  }
  views?.addEventListener('click', onClick)
  return () => {
    cancelAnimationFrame(raf)
    views?.removeEventListener('click', onClick)
  }
}
```

### Fewer requests with an atlas

Thirty-six files mean thirty-six requests. Put the frames into atlas pages instead, read cell by cell, left to right and top to bottom. Two pages of 6 × 6 hold 72 frames, and `.ktx2` pages stay compressed on the GPU, so an atlas keeps no frames decoded on the CPU.

```html
<img
  src="/spin/camera/01.avif"
  data-dio="spin"
  data-dio-atlas="/spin/camera-{0..1}.ktx2"
  data-dio-grid="6 6"
  tabindex="0"
  style="touch-action: pan-y"
/>
```

### Sparse sets and products that turn by themselves

With 24 frames or fewer, each step jumps visibly. `blend` cross-fades two neighbors by the fraction of the turn, which smooths a sparse set but reads as ghosting on a dense one, so it is off by default. `spin` turns it, in degrees a second, until the first touch, for a hero shot or a card that should catch the eye.

```html
<img
  src="/spin/vase/01.avif"
  data-dio="spin"
  data-dio-frames="/spin/vase/{01..18}.avif"
  data-dio-blend="true"
  data-dio-spin="36"
  tabindex="0"
  style="touch-action: pan-y"
/>
```

## Notes

Frames decode off the main thread, and only `cache` of them stay decoded around the current one. A 36-frame set of 960 × 640 AVIF files weighs about 630 KB here; the `low` tier loads half the frames at up to 960 px. Decide on `density` before you shoot more frames: 0.5 loads every second one.

The product stops on the frame where the pointer lets go. `inertia` adds a coast after a flick: the product turns on as far as the flick carries it in that many seconds and eases out onto a whole photo, cross-fading neighbor frames on the way so it slows down without stepping. Try 0.3 to 0.5; reduced motion turns the coast off.

`by` set to `hover` turns the product as the mouse moves over it, without a press. Touch screens have no hover, so a finger still drags it. `manual` leaves the pointer to the page entirely: keys, `frame` and `spin` turn it.

Rows of viewing angles work the same way: shoot one circle per height, set `rows`, and a vertical drag moves between them. Rows need `touch-action: none`, since a vertical swipe turns the product instead of scrolling.

## Related

- [book](/docs/effects/book.md): A cover image made a 3D book that turns to show its spine and opens on hover.
- [box](/docs/effects/box.md): A product box built from pictures of its faces: turn it, tilt it, open its lid.
- [coin](/docs/effects/coin.md): A coin, medal or token struck from a logo or a photo: it turns, catches the light and flips over.
- [device](/docs/effects/device.md): A screenshot or a video shown in a 3D phone, tablet, laptop or browser window.
- [explode](/docs/effects/explode.md): An exploded view of a model: its parts move apart as the section scrolls.
- [hotspots](/docs/effects/hotspots.md): Feature callouts pinned to points of a model, real buttons that follow it as it turns.
- [label](/docs/effects/label.md): A flat label wrapped around a can, a bottle or a jar that turns to show all of it.
- [model](/docs/effects/model.md): A glTF model fitted into the element, lit, turnable and recolored from markup.
- [Performance and quality](/docs/guides/performance.md)
- [Loading and preloading](/docs/guides/loading.md)
