Hi! I'm HIGASHIYUKI® Art Director | Photo & Videographer | Web Engineer

配色

音楽

Lo-Fi #001by ST®AND.(音源のサイト。新しいタブで開きます)

ジャンル

グラフ

カーソルを重ねた区分だけがせり上がり、中央の割合が切り替わる立体ドーナツグラフ

デモ

操作:カーソルを重ねる。「さわってみる」を押すと自動再生が止まり、マウスで動かせます。

仕様

用途
グラフ
動作
DOM+WebGL
種類
シーン
動作確認
three 0.186.0・gsap 3.15.0
公開日

しくみと調整

グラフの区分(パーツ)にカーソルを重ねると、その区分だけが外側へスーッとずれて持ち上がります。同時に輪の中央の表示が「全体 100%」から該当する区分名と割合・件数へ切り替わり、数値も前の値から滑らかにカウントアップしていきます。左側の凡例でも同じ行が白く強調され、色のついた四角いマーカーが横へ伸びて連動します。なお、ページを開いた直後は12時の位置から時計回りに区分が順番に伸びていき、1.8秒かけてひとつの輪が完成します。

ドーナツグラフの各パーツは、角を丸めた断面を円周に沿って押し出して作った独自の BufferGeometry(頂点データを直接管理する立体形状)でできています。Three.js標準の LatheGeometry でも断面を回して立体を作れますが、扇形の切り口に面が張られないうえ、伸びていく途中の状態を描くたびに立体データを作り直す必要があります。そこで、頂点の数とつながり方は最初に固定しておき、「いまどこまで伸びたか」に合わせて座標だけを書き換える方法をとりました。これにより、伸びていく先端も常に同じきれいな断面のまま描かれます。区分どうしのすき間は半径に応じて角度を微調整し、内周でも外周でも同じ幅に見えるよう整えました。

カーソルがどの区分に重なっているかは、画面の手前から奥へ仮想の線を飛ばしてぶつかった立体を調べる Raycaster で判定しています。ただし、判定の対象にしているのは実際に動いている立体ではありません。区分ごとに、ずれて持ち上がった状態までをすっぽり覆う一回り大きな見えない立体を用意し、その場に固定して置いています。動いている立体そのものに当たり判定を持たせると、境界付近にカーソルを置いたとき、区分がずれた瞬間に判定が外れて元に戻り、また当たって……とガタガタ震える誤作動が起きてしまうためです。

持ち上がるときは勢いよく出て最後になめらかに止まる0.6秒の power3.out、戻るときは前後が穏やかな0.45秒の power2.inOut を設定しました。選ばれていない区分はあえて薄くせず、本来の色のまま残しています。高さと影の差をつけるだけでも、選んだ区分は十分に際立つからです。外へずらす量を大きくすれば離れている印象は強まりますが、その分だけ外周に広い余白が必要になり、隣の区分へ落ちる影も濃くなるためバランスを見て調整します。

件数のデータはHTMLの一覧ボタンに書かれており、スクリプトがそれを読み取って立体を組み立てています。ボタンにカーソルを重ねても、キーボードでフォーカスを当てても同じ区分が持ち上がるため、立体を直接操作しなくても内訳を確認できます。なお、立体と中央の表示は一覧と同じ情報を視覚的に見せるものなので、スクリーンリーダーの読み上げ対象からは外しています。

コード

HTML
<section class="donut" aria-labelledby="donut-title">
  <div class="donut__text">
    <p class="donut__eyebrow">SURVEY</p>
    <h2 class="donut__title" id="donut-title">来店のきっかけ</h2>
    <p class="donut__note">2026年10月・回答1,240件</p>
    <!-- 区分の件数は data-count。色は style.css の --color。script.js がこの一覧から立体を組む -->
    <ul class="donut__legend">
      <li><button type="button" data-count="422"><span class="donut__name">SNS</span><span class="donut__share">34%</span></button></li>
      <li><button type="button" data-count="298"><span class="donut__name">知人の紹介</span><span class="donut__share">24%</span></button></li>
      <li><button type="button" data-count="236"><span class="donut__name">検索</span><span class="donut__share">19%</span></button></li>
      <li><button type="button" data-count="174"><span class="donut__name">通りがかり</span><span class="donut__share">14%</span></button></li>
      <li><button type="button" data-count="110"><span class="donut__name">チラシ</span><span class="donut__share">9%</span></button></li>
    </ul>
  </div>
  <!-- 立体と中央の表示は一覧と同じ内容を描くだけなので、スクリーンリーダーからは外す -->
  <div class="donut__stage" aria-hidden="true">
    <canvas></canvas>
    <p class="donut__readout">
      <span class="donut__label">全体</span>
      <span class="donut__value"><b>100</b>%</span>
      <span class="donut__count"><b>1,240</b>件</span>
    </p>
  </div>
</section>

CSS
.donut {
  /* 色はここで決める。script.js が --color・--ink・--ground を読んで、立体と影と光の色にする */
  --bg: #f2f1ed;
  --surface: #ffffff;
  --ink: #262626;
  --mute: #898989;
  --mute-small: #6b6b6b; /* 16px 未満の文字 */
  --line: rgba(38, 38, 38, 0.12);
  --ground: #cfcac0; /* 下から回り込む光 */
  display: grid;
  grid-template-columns: minmax(0, 320px) minmax(0, 832px);
  justify-content: center;
  align-items: center;
  gap: 32px;
  padding: 64px clamp(16px, 7vw, 96px);
  background: var(--bg);
  color: var(--ink);
  font-variant-numeric: tabular-nums;
}

/* 区分の色。パレットの色の彩度を上げた値で、隣り合う区分は明るさの差で見分ける */
.donut__legend li:nth-child(1) { --color: #375f79; }
.donut__legend li:nth-child(2) { --color: #ca6359; }
.donut__legend li:nth-child(3) { --color: #ab9f3a; }
.donut__legend li:nth-child(4) { --color: #4c85b3; }
.donut__legend li:nth-child(5) { --color: #bd894c; }

.donut__eyebrow { margin: 0; color: var(--mute-small); font-size: 13px; font-weight: 700; line-height: 1; letter-spacing: 0.14em; }
.donut__title { margin: 20px 0 0; font-size: clamp(32px, 5vw, 44px); font-weight: 800; line-height: 1.1; letter-spacing: -0.02em; }
.donut__note { margin: 16px 0 0; color: var(--mute); font-size: 16px; font-weight: 600; line-height: 1.5; letter-spacing: 0.04em; }

.donut__legend { margin: 32px 0 0; padding: 0; border-top: 1px solid var(--line); list-style: none; }
/* --lift(その区分の持ち上がり)と --dim(ほかの区分の持ち上がり)は、どちらも 0〜1 で script.js が毎コマ入れる */
.donut__legend button {
  display: flex;
  align-items: center;
  gap: 14px;
  width: 100%;
  height: 52px;
  padding: 0 14px;
  border: 0;
  border-radius: 4px;
  box-shadow: inset 0 -1px 0 var(--line);
  background: color-mix(in srgb, var(--surface) calc(var(--lift, 0) * 100%), transparent);
  color: inherit;
  font: inherit;
  font-size: 15px;
  line-height: 1;
  letter-spacing: 0.04em;
  text-align: left;
  cursor: pointer;
}
/* 色の印。選んだ区分では横に伸びる */
.donut__legend button::before {
  content: "";
  flex: none;
  width: calc(12px + var(--lift, 0) * 16px);
  height: 12px;
  border-radius: 3px;
  background: var(--color);
}
.donut__legend button > span { opacity: calc(1 - var(--dim, 0) * 0.55); }
.donut__name { flex: 1; font-weight: 600; }
.donut__share { font-size: 16px; font-weight: 800; letter-spacing: 0; }
.donut__legend button:focus-visible { outline: 2px solid var(--ink); outline-offset: -2px; }

/* 立体の表示領域。中央の表示もこの中に置く */
.donut__stage { position: relative; aspect-ratio: 832 / 720; container-type: inline-size; overflow: clip; }
.donut__stage canvas { display: block; width: 100%; height: 100%; }

/* 輪の穴の中の表示。位置(left・top)は script.js が穴の見えている所の真ん中に入れる */
.donut__readout {
  position: absolute;
  left: 50%;
  top: 50%;
  display: grid;
  justify-items: center;
  gap: 10px;
  margin: 0;
  translate: -50% -50%;
  line-height: 1;
  text-align: center;
  white-space: nowrap;
  pointer-events: none;
}
.donut__label { color: var(--mute); font-size: clamp(12px, 1.8cqi, 15px); font-weight: 700; letter-spacing: 0.04em; }
.donut__value { font-size: clamp(14px, 2.9cqi, 24px); font-weight: 700; }
.donut__value b { margin-right: 2px; font-size: clamp(24px, 6.7cqi, 56px); font-weight: 800; letter-spacing: -0.02em; }
.donut__count { color: var(--mute-small); font-size: clamp(11px, 1.6cqi, 13px); font-weight: 600; letter-spacing: 0.04em; }
.donut__count b { font-weight: inherit; }

@media (max-width: 860px) {
  .donut { grid-template-columns: minmax(0, 1fr); padding: 48px 16px; }
  .donut__stage { margin: 0 -16px; } /* 狭い画面では、左右の余白まで使って輪を大きくする */
  .donut__readout { gap: 4px; }
}

JavaScript
import * as THREE from "three";
import { gsap } from "gsap";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";

const RI = 1.2, RO = 2.3, H = 0.5, BEVEL = 0.07, GAP = 0.07; // 内周と外周の半径・厚み・上の角の丸み・区分の間のすき間
const EXPLODE = 0.3, LIFT = 0.28, RISE = 0.6, FALL = 0.45, COUNT = 0.6; // せり出す量・持ち上がる量・せり出す秒数(power3.out)・戻る秒数(power2.inOut)・数字を数える秒数
const ELEVATION = 0.8, AZIMUTH = -0.12, DISTANCE = 12.5, SHADE = 0.5; // カメラの見下ろす角度・向き・距離と、材質に渡す色の倍率
const TAU = Math.PI * 2, reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const time = (seconds) => (reduceMotion ? 0 : seconds); // 動きを減らす設定では、その場で切り替える

// 断面 [半径, 高さ, 法線の半径方向, 法線の高さ方向]。内側の壁 → 丸めた角 → 上面 → 丸めた角 → 外側の壁 → 底。底の角は法線の違う点を 2 つ重ねて折る
function profile(ri, ro, h, b) {
  const pts = [[ri, 0, 0, -1], [ri, 0, -1, 0]];
  for (const [cr, from] of [[ri + b, Math.PI], [ro - b, Math.PI / 2]]) for (let k = 0, a = from; k <= 4; a = from - (++k * Math.PI) / 8) pts.push([cr + b * Math.cos(a), h - b + b * Math.sin(a), Math.cos(a), Math.sin(a)]);
  return [...pts, [ro, 0, 1, 0], [ro, 0, 0, -1], [ri, 0, 0, -1]];
}
// 断面を角度の方向へ掃いた扇形の立体。draw(to) で、区分 a0〜a1 のうち to までを描く(輪が伸びる途中も、同じ断面のまま)
function slice(prof, a0, a1, gap) {
  const P = prof.length, steps = Math.max(8, Math.ceil((a1 - a0) / 0.044)), index = [], geometry = new THREE.BufferGeometry();
  const outline = prof.filter((p, i) => i === 0 || p[0] !== prof[i - 1][0] || p[1] !== prof[i - 1][1]).slice(0, -1), n = outline.length;
  const base = (steps + 1) * P, pos = new Float32Array((base + 2 * n) * 3), nor = new Float32Array(pos.length);
  for (let j = 0; j < steps; j++) for (let i = 0, a = j * P; i < P - 1; i++, a++) index.push(a, a + P, a + 1, a + 1, a + P, a + P + 1);
  for (const t of THREE.ShapeUtils.triangulateShape(outline.map(([r, y]) => new THREE.Vector2(r, y)), [])) { // 両端の面。始まりの側は逆向きにして外へ向ける
    const [p, q, r] = t.map((k) => outline[k]), [x, y, z] = (q[0] - p[0]) * (r[1] - p[1]) > (q[1] - p[1]) * (r[0] - p[0]) ? t : [t[0], t[2], t[1]];
    index.push(base + x, base + z, base + y, base + n + x, base + n + y, base + n + z);
  }
  geometry.setIndex(index).setAttribute("position", new THREE.BufferAttribute(pos, 3)).setAttribute("normal", new THREE.BufferAttribute(nor, 3));
  let k = 0, to = a1;
  const put = (r, y, nr, ny, side, j) => { // 境目の側は、半径ごとに角度を詰めて、すき間を内周でも外周でも同じ幅にする
    const s = a0 + gap / 2 / r, e = Math.max(s, Math.min(to, a1 - gap / 2 / r)), th = side ? (side < 0 ? s : e) : s + ((e - s) * j) / steps;
    pos.set([r * Math.sin(th), y, -r * Math.cos(th)], k * 3);
    nor.set(side ? [side * Math.cos(th), 0, side * Math.sin(th)] : [nr * Math.sin(th), ny, -nr * Math.cos(th)], k++ * 3);
  };
  return { geometry, draw: (until) => {
    [k, to] = [0, until]; for (let j = 0; j <= steps; j++) for (const [r, y, nr, ny] of prof) put(r, y, nr, ny, 0, j);
    for (const side of [-1, 1]) for (const [r, y] of outline) put(r, y, 0, 0, side);
    geometry.attributes.position.needsUpdate = geometry.attributes.normal.needsUpdate = true; geometry.computeBoundingSphere();
  } };
}

document.querySelectorAll(".donut").forEach((chart) => {
  const css = (name, el = chart) => getComputedStyle(el).getPropertyValue(name).trim(), stage = chart.querySelector(".donut__stage"), buttons = [...chart.querySelectorAll(".donut__legend button")];
  const readout = chart.querySelector(".donut__readout"), label = readout.querySelector(".donut__label"), [share, count] = readout.querySelectorAll("b");
  const renderer = new THREE.WebGLRenderer({ canvas: stage.querySelector("canvas"), antialias: true, alpha: true }); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
  renderer.toneMapping = THREE.NeutralToneMapping; Object.assign(renderer.shadowMap, { enabled: true, type: THREE.PCFShadowMap });
  const scene = new THREE.Scene(), pmrem = new THREE.PMREMGenerator(renderer), room = new RoomEnvironment(), env = pmrem.fromScene(room, 0.04);
  const camera = new THREE.PerspectiveCamera(30, 832 / 720, 0.1, 100); // 表示領域の縦横比は CSS の aspect-ratio で固定
  camera.position.set(Math.sin(AZIMUTH), 0, Math.cos(AZIMUTH)).multiplyScalar(DISTANCE * Math.cos(ELEVATION)).y = DISTANCE * Math.sin(ELEVATION);
  camera.lookAt(0, 0.1, 0.15); camera.updateMatrixWorld(); scene.environment = env.texture; room.dispose(); pmrem.dispose();
  const sun = new THREE.DirectionalLight("#ffffff", 1.6); sun.position.set(-4, 10, 5); sun.castShadow = true; sun.shadow.mapSize.set(2048, 2048);
  Object.assign(sun.shadow.camera, { left: -4, right: 4, top: 4, bottom: -4, near: 1, far: 30 }); Object.assign(sun.shadow, { radius: 4, bias: -0.0004, normalBias: 0.02 });
  const ground = new THREE.Mesh(new THREE.PlaneGeometry(12, 12), new THREE.ShadowMaterial({ color: css("--ink"), opacity: 0.16 })); // 影だけを受ける床
  ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true; scene.add(sun, new THREE.HemisphereLight("#ffffff", css("--ground"), 0.9), ground);
  // 区分は一覧のボタンから作る。角度は件数の割合、色はボタンの --color。当たり判定は、休みの位置でせり出すぶん大きくした見えない立体に取る
  const counts = buttons.map((b) => Number(b.dataset.count)), total = counts.reduce((a, b) => a + b, 0), prof = profile(RI, RO, H, BEVEL), hitProf = profile(RI, RO + EXPLODE, H + LIFT, 0.001);
  let at = 0; const slices = buttons.map((button, i) => {
    const a0 = at, a1 = (at += (counts[i] / total) * TAU), body = slice(prof, a0, a1, GAP), hit = slice(hitProf, a0, a1, 0);
    const mesh = new THREE.Mesh(body.geometry, new THREE.MeshStandardMaterial({ color: new THREE.Color(css("--color", button)).multiplyScalar(SHADE), roughness: 0.42, envMapIntensity: 0.55 }));
    const hitMesh = Object.assign(new THREE.Mesh(hit.geometry), { userData: { index: i } }); hit.draw(a1); hitMesh.updateMatrixWorld(); scene.add(Object.assign(mesh, { castShadow: true, receiveShadow: true, frustumCulled: false }));
    return { button, a0, a1, mid: (a0 + a1) / 2, body, mesh, hitMesh, name: button.querySelector(".donut__name").textContent, share: (counts[i] / total) * 100, count: counts[i], v: 0 };
  });
  const rest = { name: label.textContent, share: 100, count: total }, ring = { head: reduceMotion ? TAU : 0 }, center = { share: 100, count: total };
  const write = () => { share.textContent = Math.round(center.share); count.textContent = Math.round(center.count).toLocaleString("ja-JP"); };
  const far = new THREE.Vector3(0, 0, -RI).project(camera), near = new THREE.Vector3(0, H, RI).project(camera); // 中央の表示は、穴の見えている所(奥の内壁の下端と手前の上面の縁の間)の真ん中に置く
  Object.assign(readout.style, { left: `${((far.x + 1) / 2) * 100}%`, top: `${((2 - far.y - near.y) / 4) * 100}%` });
  let hovered = -1, row = -1, active = -1, swap; // せり出す区分は、立体に重ねた区分 → 一覧で重ねたかフォーカスした行 の順に決める
  const update = () => {
    const next = hovered >= 0 ? hovered : row, item = slices[next] ?? rest;
    if (next === active) return; active = next; // 前のトゥイーンを止めて、いまの値から向きを変える
    slices.forEach((s, i) => gsap.to(s, { v: i === next ? 1 : 0, duration: time(i === next ? RISE : FALL), ease: i === next ? "power3.out" : "power2.inOut", overwrite: true }));
    gsap.to(center, { share: item.share, count: item.count, duration: time(COUNT), ease: "power2.out", overwrite: true, onUpdate: write });
    swap?.kill(); swap = gsap.timeline() // 区分名は、前の名前が上へ抜けきってから次の名前が下から入る(2 つを重ねない)
      .to(label, { y: -8, opacity: 0, duration: time(0.15), ease: "power2.in" }).call(() => { label.textContent = item.name; })
      .fromTo(label, { y: 8, opacity: 0 }, { y: 0, opacity: 1, duration: time(0.15), ease: "power2.out" });
  };
  const raycaster = new THREE.Raycaster(), ndc = new THREE.Vector2(); ["pointermove", "pointerdown"].forEach((type) => stage.addEventListener(type, (e) => { // タッチ端末では、タップした区分がせり出す
    const r = stage.getBoundingClientRect(); raycaster.setFromCamera(ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), camera);
    hovered = raycaster.intersectObjects(slices.map((s) => s.hitMesh), false)[0]?.object.userData.index ?? -1; stage.style.cursor = hovered >= 0 ? "pointer" : ""; update();
  }));
  stage.addEventListener("pointerleave", (e) => { if (e.pointerType !== "touch") { hovered = -1; update(); } });
  // 一覧の行は、カーソルを重ねてもキーボードでフォーカスしても、同じ区分がせり出す
  buttons.forEach((b, i) => [["pointerenter", i], ["pointerleave", -1], ["focus", i], ["blur", -1]].forEach(([type, value]) => b.addEventListener(type, () => { row = value; update(); })));
  const draw = () => {
    slices.forEach((s, i) => { // 輪の伸びた所までを描く。頂点は、変わったときだけ書き直す
      const to = Math.min(s.a1, ring.head); if ((s.mesh.visible = to > s.a0) && to !== s.to) s.body.draw((s.to = to));
      s.mesh.position.set(Math.sin(s.mid) * EXPLODE * s.v, LIFT * s.v, -Math.cos(s.mid) * EXPLODE * s.v);
      s.button.style.setProperty("--lift", s.v.toFixed(3)); s.button.style.setProperty("--dim", Math.max(0, ...slices.filter((_, k) => k !== i).map((o) => o.v)).toFixed(3));
    }); renderer.render(scene, camera);
  };
  // 画面に入ったら、12 時から時計回りに区分が順に伸びて輪になり、穴の中の表示が下から現れる(1 回だけ)
  const grow = reduceMotion ? null : gsap.timeline({ paused: true }).to(ring, { head: TAU, duration: 1.8, ease: "power2.inOut" })
    .fromTo(readout, { opacity: 0, y: 10 }, { opacity: 1, y: 0, duration: 0.5, ease: "power2.out" }, 1.4);
  const resize = new ResizeObserver(() => { renderer.setSize(stage.clientWidth, stage.clientHeight, false); draw(); }); // 大きさは CSS が決める
  const view = new IntersectionObserver(([e]) => { if (e.isIntersecting) grow?.play(); renderer.setAnimationLoop(e.isIntersecting ? draw : null); }, { threshold: 0.3 }); resize.observe(stage); view.observe(chart);
  chart.destroy = () => { // PJAX でセクションごと破棄するときに呼ぶ。放っておくと WebGL のコンテキストが積み上がる
    renderer.setAnimationLoop(null); resize.disconnect(); view.disconnect(); grow?.kill(); swap?.kill(); gsap.killTweensOf([center, ...slices]);
    for (const s of [...slices.flatMap((s) => [s.body.geometry, s.hitMesh.geometry, s.hitMesh.material, s.mesh.material]), ground.geometry, ground.material, env, renderer]) s.dispose(); renderer.forceContextLoss();
  };
});

グラフをすべて見る