Try 'magnetic button'
View code

Specification

Catalogue
No. 82 of 110
Interaction
Drag
Element
Media
Preview
Live component
Imports
react 19.3.1
Added

Notes

Drag to turn a product and see its back and underside, or jump to a labelled view.

Shoppers want to see the back, the connections and the feet before they buy. Nothing spins on its own, and the labelled views get to each side in one tap.

Built differently from the library: a CSS 3D object (six faces with preserve-3d), not three.js, so no WebGL and no added dependency. Labelled views glide 600ms cubic-bezier(.77, 0, .175, 1), the short way round; dragging follows the hand. Arrow keys turn it 15 degrees; the label says which side is showing. A real build with a scanned product uses a glTF model loaded on request behind a still photo.

The names, figures and pictures in the demo are sample content; a real build uses the client's own.

Code

React and plain CSS
"use client";

import { useRef, useState, type KeyboardEvent, type PointerEvent } from "react";
import { reducedNow } from "@/components/pieces/motion-helpers";
import type { LivePreviewProps } from "@/components/live/types";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./model-viewer.css";

const VIEWS = [
  { id: "front", label: "Front", x: -10, y: -24 },
  { id: "side", label: "Side", x: -10, y: -90 },
  { id: "back", label: "Back", x: -10, y: 180 },
  { id: "under", label: "Underside", x: 72, y: -20 },
] as const;

function viewName(x: number, y: number): string {
  if (x > 45) return "the underside";
  if (x < -45) return "the top";
  const a = ((y % 360) + 360) % 360;
  if (a < 45 || a > 315) return "the front";
  if (a > 135 && a < 225) return "the back";
  return "a side";
}

function ModelViewerDemo() {
  const [rot, setRot] = useState({ x: -10, y: -24 });
  const [glide, setGlide] = useState(false);
  const drag = useRef<{ x: number; y: number; rx: number; ry: number; id: number } | null>(null);
  const clampX = (v: number) => Math.max(-80, Math.min(80, v));

  const onDown = (e: PointerEvent<HTMLDivElement>) => {
    drag.current = { x: e.clientX, y: e.clientY, rx: rot.x, ry: rot.y, id: e.pointerId };
    setGlide(false);
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const onMove = (e: PointerEvent<HTMLDivElement>) => {
    const d = drag.current;
    if (!d || d.id !== e.pointerId) return;
    setRot({ x: clampX(d.rx - (e.clientY - d.y) * 0.4), y: d.ry + (e.clientX - d.x) * 0.5 });
  };
  const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
    const step: Record<string, [number, number]> = { ArrowLeft: [0, -15], ArrowRight: [0, 15], ArrowUp: [-10, 0], ArrowDown: [10, 0] };
    const m = step[e.key];
    if (!m) return;
    e.preventDefault();
    setGlide(!reducedNow());
    setRot((r) => ({ x: clampX(r.x + m[0]), y: r.y + m[1] }));
  };
  const show = (v: (typeof VIEWS)[number]) => {
    setGlide(!reducedNow());
    // Turn the short way round from wherever the object is now.
    setRot((r) => {
      const turns = Math.round((r.y - v.y) / 360);
      return { x: v.x, y: v.y + turns * 360 };
    });
  };

  return (
    <div className="dm">
      <div className="mv">
        <div
          className="mv-stage"
          tabIndex={0}
          role="img"
          aria-roledescription="3D view"
          aria-label={`Oak bedside cabinet, showing ${viewName(rot.x, rot.y)}. Drag or use the arrow keys to turn it.`}
          onPointerDown={onDown}
          onPointerMove={onMove}
          onPointerUp={() => (drag.current = null)}
          onPointerCancel={() => (drag.current = null)}
          onKeyDown={onKey}
        >
          <div className="mv-obj" data-glide={glide || undefined} style={{ transform: `rotateX(${rot.x}deg) rotateY(${rot.y}deg)` }}>
            <div className="mv-face mv-front">
              <span className="mv-drawer">
                <i />
              </span>
              <span className="mv-door">
                <i />
              </span>
            </div>
            <div className="mv-face mv-back">
              <span className="mv-hole" />
              <span className="mv-stamp">Back panel, 2 cable holes</span>
              <span className="mv-hole mv-hole-2" />
            </div>
            <div className="mv-face mv-right" />
            <div className="mv-face mv-left" />
            <div className="mv-face mv-top" />
            <div className="mv-face mv-bottom">
              <i />
              <i />
              <i />
              <i />
              <span className="mv-stamp">Solid oak feet, felt pads</span>
            </div>
          </div>
        </div>
        <div className="mv-views" role="group" aria-label="Show a view">
          {VIEWS.map((v) => (
            <button key={v.id} type="button" className="dm-btn" onClick={() => show(v)}>
              {v.label}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// What a hovered card shows: the piece used the way a visitor would.
const TOUR: Tour = [
  { click: ".dm-btn", nth: 1 },
  { click: ".dm-btn", nth: 2 },
  { click: ".dm-btn", nth: 3 },
  { click: ".dm-btn", nth: 0 },
];

export default function ModelViewerEntry(props: LivePreviewProps) {
  return (
    <PieceStage {...props} label="Product you can turn" sample tour={TOUR}>
      <ModelViewerDemo />
    </PieceStage>
  );
}

More like this

Before and after slider

DragMedia and galleries

Image panels that widen

Hover, Layout AnimationMedia and galleries

Photo grid that opens into the photo

Layout AnimationMedia and galleries

Zoom into a photo where you point

PressMedia and galleries

Focal point for every crop

DragMedia and galleries

Price range over the prices it filters

DragForms and inputs