04충돌 방지 — 노드 반지름만큼 서로 밀어내 겹침이 없다
두 노드의 중심 거리가 반지름 합보다 가까워지면 즉시 밀어내는 규칙을 힘 계산에 끼워 넣으면 라벨이 서로 가려지지 않는데, 실제 서비스에 바로 쓸 수 있게 읽기를 지키는 보정 항목입니다.
쓰임조직도, 지식 그래프 UI
arcMath.hypotrequestAnimationFramebeginPath

<main class="stage">
<div class="gd is-demo" id="gdRoot" role="img" aria-label="노드 반지름만큼 서로 밀어내 겹치지 않는 실험판" tabindex="0">
<canvas class="gd__cv" id="gdCv"></canvas>
<p class="gd__hint">
<span class="gd__title">충돌 방지</span>
<span class="gd__desc">반지름 합보다 가까워지면 즉시 밀어내 라벨이 겹치지 않습니다</span>
</p>
<div class="gd__bar">
<span class="gd__meta">노드 22개 · 크기 다양 · rAF</span>
<span class="gd__meta gd__meta--dim">arc · Math.hypot · beginPath</span>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 충돌 방지(04) — 무대 종이. 힘 계산 뒤 위치 보정 패스까지 전부 rAF 캔버스가 만든다.
$gd-stage: #f1ecdf;
@include stage($gd-stage);
$gd-panel: #e4dcc8; // 캔버스 바닥 — 무대보다 어두운 모래
$gd-text: #3c3324; // 라벨 글자 — 짙은 카키 브라운
$gd-node: #7d8f6a; // 노드 — 올리브 세이지
$gd-ring: #3c3324; // 노드 테두리 — 짙은 카키(경계 강조)
$duration: $dur-loop;
$easing: $ease-out;
$color: $gd-node;
.gd {
--gd-panel: #{$gd-panel};
--gd-node: #{$gd-node};
--gd-ring: #{$gd-ring};
position: relative;
display: flex; flex-direction: column;
width: 100%; height: 100%; min-height: 164px;
overflow: hidden;
}
.gd__cv { position: absolute; inset: 0; display: block; width: 100%; height: 100%; }
.gd__hint {
position: relative; z-index: 1;
display: flex; flex-direction: column; gap: 0; margin: 0;
padding: $sp-2 $sp-3 0;
font-weight: 700; font-size: clamp(10px, 2.8vw, 12px); line-height: 1.35;
color: $gd-text;
}
.gd__title { text-shadow: 0 1px 6px rgba($gd-panel, .9); }
.gd__desc {
margin-top: $sp-1;
font-weight: 500; font-size: clamp(9px, 2.4vw, 10px); line-height: 1.4;
color: rgba($gd-text, .78);
text-shadow: 0 1px 6px rgba($gd-panel, .9);
}
.gd__bar {
position: relative; z-index: 1;
margin-top: auto;
display: flex; align-items: baseline; justify-content: space-between; gap: $sp-2;
padding: 0 $sp-3 $sp-2;
}
.gd__meta {
font-size: 10px; font-weight: 500; color: rgba($gd-text, .8);
background: rgba($gd-panel, .82);
border-radius: $r-xs;
padding: 4px $sp-1;
}
.gd:focus-visible { outline: 2px solid $gd-node; outline-offset: -2px; }
@media (max-width: 340px) {
.gd__meta--dim { display: none; }
}
@media (prefers-reduced-motion: reduce) {
.gd.is-still { cursor: default !important; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #f1ecdf;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.gd {
--gd-panel: #e4dcc8;
--gd-node: #7d8f6a;
--gd-ring: #3c3324;
position: relative;
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
min-height: 164px;
overflow: hidden;
}
.gd__cv {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
}
.gd__hint {
position: relative;
z-index: 1;
display: flex;
flex-direction: column;
gap: 0;
margin: 0;
padding: 8px 12px 0;
font-weight: 700;
font-size: clamp(10px, 2.8vw, 12px);
line-height: 1.35;
color: #3c3324;
}
.gd__title {
text-shadow: 0 1px 6px rgba(228, 220, 200, 0.9);
}
.gd__desc {
margin-top: 4px;
font-weight: 500;
font-size: clamp(9px, 2.4vw, 10px);
line-height: 1.4;
color: rgba(60, 51, 36, 0.78);
text-shadow: 0 1px 6px rgba(228, 220, 200, 0.9);
}
.gd__bar {
position: relative;
z-index: 1;
margin-top: auto;
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
padding: 0 12px 8px;
}
.gd__meta {
font-size: 10px;
font-weight: 500;
color: rgba(60, 51, 36, 0.8);
background: rgba(228, 220, 200, 0.82);
border-radius: 4px;
padding: 4px 4px;
}
.gd:focus-visible {
outline: 2px solid #7d8f6a;
outline-offset: -2px;
}
@media (max-width: 340px) {
.gd__meta--dim {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
.gd.is-still {
cursor: default !important;
}
}// 충돌 방지(04) — 척력만으로는 순간적으로 겹칠 수 있다. 매 프레임 위치를 적분한
// 뒤, 반지름 합보다 중심 거리가 가까운 쌍을 찾아 그 자리에서 즉시 밀어내는
// 보정 패스(하드 충돌 해소)를 한 겹 더 끼운다 — 힘이 아니라 위치 자체를 고친다.
(function () {
// ── 변형 상수 블록 ──
var N = 22;
var REPEL = 420;
var SPEED = 78; // 자유 유영 속도(무작위 방향 힘의 크기)
// ────────────────────────
var DAMP = 0.965;
var CENTER_K = 0.0016;
var OMEGA = 0.6;
var RMIN = 6, RMAX = 15;
var root = document.getElementById('gdRoot');
var cvEl = document.getElementById('gdCv');
if (!root || !cvEl) return;
var css = getComputedStyle(root);
function tokRGB(name) {
var s = css.getPropertyValue(name).trim();
var hx = s.length === 4
? s.charAt(1) + s.charAt(1) + s.charAt(2) + s.charAt(2) + s.charAt(3) + s.charAt(3)
: s.slice(1);
return [parseInt(hx.slice(0, 2), 16), parseInt(hx.slice(2, 4), 16), parseInt(hx.slice(4, 6), 16)];
}
var C_PANEL = tokRGB('--gd-panel');
var C_NODE = tokRGB('--gd-node');
var C_RING = tokRGB('--gd-ring');
var ctx = cvEl.getContext('2d');
var W = 0, H = 0, dpr = Math.min(window.devicePixelRatio || 1, 2);
function makeRand(seed) {
var st = seed >>> 0;
return function () {
st = (st + 0x6D2B79F5) >>> 0;
var t = st;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
var rand = makeRand(0x327004);
var px, py, vx, vy, rad;
function buildGraph() {
px = new Float32Array(N); py = new Float32Array(N);
vx = new Float32Array(N); vy = new Float32Array(N);
rad = new Float32Array(N);
for (var i = 0; i < N; i++) {
px[i] = rand() * W; py[i] = rand() * H;
rad[i] = RMIN + rand() * (RMAX - RMIN);
}
}
function fit() {
var r = root.getBoundingClientRect();
W = Math.round(r.width); H = Math.round(r.height);
cvEl.width = Math.round(W * dpr); cvEl.height = Math.round(H * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
buildGraph();
}
function step(dt) {
var fx = new Float32Array(N), fy = new Float32Array(N);
for (var i = 0; i < N; i++) {
for (var j = i + 1; j < N; j++) {
var dx = px[j] - px[i], dy = py[j] - py[i];
var d = Math.hypot(dx, dy) || 0.001;
var d2 = d * d; if (d2 < 4) d2 = 4;
var f = REPEL / d2;
var ux = dx / d, uy = dy / d;
fx[i] -= ux * f; fy[i] -= uy * f;
fx[j] += ux * f; fy[j] += uy * f;
}
}
var cx = W / 2, cy = H / 2;
for (var n = 0; n < N; n++) {
fx[n] += (cx - px[n]) * CENTER_K;
fy[n] += (cy - py[n]) * CENTER_K;
fx[n] += (rand() - 0.5) * SPEED;
fy[n] += (rand() - 0.5) * SPEED;
vx[n] = (vx[n] + fx[n] * dt) * DAMP;
vy[n] = (vy[n] + fy[n] * dt) * DAMP;
px[n] += vx[n] * dt; py[n] += vy[n] * dt;
}
// 하드 충돌 해소 — 반지름 합보다 가까운 쌍을 그 자리에서 절반씩 밀어낸다
for (var a = 0; a < N; a++) {
for (var b = a + 1; b < N; b++) {
var ddx = px[b] - px[a], ddy = py[b] - py[a];
var dist = Math.hypot(ddx, ddy) || 0.001;
var minDist = rad[a] + rad[b];
if (dist < minDist) {
var push = (minDist - dist) / 2;
var nx = ddx / dist, ny = ddy / dist;
px[a] -= nx * push; py[a] -= ny * push;
px[b] += nx * push; py[b] += ny * push;
}
}
}
}
function rotateAll(dtheta) {
var cx = W / 2, cy = H / 2, cs = Math.cos(dtheta), sn = Math.sin(dtheta);
for (var i = 0; i < N; i++) {
var rx = px[i] - cx, ry = py[i] - cy;
px[i] = cx + rx * cs - ry * sn;
py[i] = cy + rx * sn + ry * cs;
}
}
function draw() {
ctx.clearRect(0, 0, W, H);
ctx.fillStyle = 'rgb(' + C_PANEL.join(',') + ')';
ctx.fillRect(0, 0, W, H);
for (var i = 0; i < N; i++) {
ctx.beginPath();
ctx.fillStyle = 'rgb(' + C_NODE.join(',') + ')';
ctx.arc(px[i], py[i], rad[i], 0, Math.PI * 2);
ctx.fill();
ctx.lineWidth = 1;
ctx.strokeStyle = 'rgba(' + C_RING.join(',') + ',0.7)';
ctx.stroke();
}
}
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var t0 = -1, last = -1;
function frame(now) {
if (t0 < 0) { t0 = now; last = now; }
var dt = Math.min((now - last) / 1000, 0.05); last = now;
step(dt);
rotateAll(OMEGA * dt);
draw();
requestAnimationFrame(frame);
}
function settle() {
for (var s = 0; s < 260; s++) step(1 / 60);
draw();
}
window.addEventListener('resize', function () {
fit();
if (reduce) settle();
});
fit();
if (reduce) {
settle();
root.classList.add('is-still');
} else {
requestAnimationFrame(frame);
}
})();// GraphForceCollisionAvoid — vanilla 판(run/327/demo/04-graph-force-collision-avoid/index.html) 의 React 포트.
// 척력만으로는 순간적으로 겹칠 수 있다. 매 프레임 위치를 적분한 뒤, 반지름 합보다 중심 거리가
// 가까운 쌍을 찾아 그 자리에서 즉시 밀어내는 보정 패스(하드 충돌 해소)를 한 겹 더 끼운다 —
// 힘이 아니라 위치 자체를 고친다. 전체는 rotateAll 로 천천히 강체 회전한다.
import { useEffect, useRef, useState } from "react";
import type { CSSProperties } from "react";
import styles from "./GraphForceCollisionAvoid.module.scss";
export type GraphForceCollisionAvoidProps = {
duration?: string;
easing?: string;
color?: string;
n?: number;
repel?: number;
speed?: number; // 자유 유영 속도(무작위 방향 힘의 크기)
};
// ── 변형 상수(기본값) — vanilla 판과 동일 ──
const N = 22;
const REPEL = 420;
const SPEED = 78;
const DAMP = 0.965;
const CENTER_K = 0.0016;
const OMEGA = 0.6;
const RMIN = 6, RMAX = 15;
const SEED = 0x327004;
type Vars = CSSProperties & { "--duration"?: string; "--easing"?: string; "--color"?: string };
type Box<T> = { current: T };
type RGB = [number, number, number];
const BOARD_LABEL = "노드 반지름만큼 서로 밀어내 겹치지 않는 실험판";
const META_LEFT = "노드 22개 · 크기 다양 · rAF";
const META_RIGHT = "arc · Math.hypot · beginPath";
const HINT_TITLE = "충돌 방지";
const HINT_DESC = "반지름 합보다 가까워지면 즉시 밀어내 라벨이 겹치지 않습니다";
function makeRand(seed: number): () => number {
let st = seed >>> 0;
return function () {
st = (st + 0x6d2b79f5) >>> 0;
let t = st;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export default function GraphForceCollisionAvoid({
duration = "2s",
easing = "ease-out",
color = "#7d8f6a",
n = N,
repel = REPEL,
speed = SPEED
}: GraphForceCollisionAvoidProps) {
const rootRef = useRef<HTMLDivElement | null>(null);
const cvRef = useRef<HTMLCanvasElement | null>(null);
const ctxRef = useRef<CanvasRenderingContext2D | null>(null);
const colRef = useRef<{ panel: RGB; node: RGB; ring: RGB } | null>(null);
const wRef = useRef(0) as Box<number>;
const hRef = useRef(0) as Box<number>;
const rafRef = useRef(0) as Box<number>;
const randRef = useRef(makeRand(SEED)) as Box<() => number>;
const pxRef = useRef<Float32Array | null>(null);
const pyRef = useRef<Float32Array | null>(null);
const vxRef = useRef<Float32Array | null>(null);
const vyRef = useRef<Float32Array | null>(null);
const radRef = useRef<Float32Array | null>(null);
const [still, setStill] = useState(false);
const vars: Vars = { "--duration": duration, "--easing": easing, "--color": color };
function reduced(): boolean {
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
function tokRGB(root: HTMLDivElement, name: string): RGB {
const s = getComputedStyle(root).getPropertyValue(name).trim();
const hx = s.length === 4
? s.charAt(1) + s.charAt(1) + s.charAt(2) + s.charAt(2) + s.charAt(3) + s.charAt(3)
: s.slice(1);
return [parseInt(hx.slice(0, 2), 16), parseInt(hx.slice(2, 4), 16), parseInt(hx.slice(4, 6), 16)];
}
function buildGraph(): void {
const rand = randRef.current;
const W = wRef.current, H = hRef.current;
const px = new Float32Array(n), py = new Float32Array(n);
const vx = new Float32Array(n), vy = new Float32Array(n);
const rad = new Float32Array(n);
for (let i = 0; i < n; i++) {
px[i] = rand() * W; py[i] = rand() * H;
rad[i] = RMIN + rand() * (RMAX - RMIN);
}
pxRef.current = px; pyRef.current = py; vxRef.current = vx; vyRef.current = vy;
radRef.current = rad;
}
function fit(): void {
const root = rootRef.current;
const cv = cvRef.current;
const ctx = ctxRef.current;
if (!root || !cv || !ctx) return;
const r = root.getBoundingClientRect();
const dpr = Math.min(window.devicePixelRatio || 1, 2);
wRef.current = Math.round(r.width);
hRef.current = Math.round(r.height);
cv.width = Math.round(wRef.current * dpr);
cv.height = Math.round(hRef.current * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
buildGraph();
}
function step(dt: number): void {
const px = pxRef.current, py = pyRef.current, vx = vxRef.current, vy = vyRef.current, rad = radRef.current;
const rand = randRef.current;
const W = wRef.current, H = hRef.current;
if (!px || !py || !vx || !vy || !rad) return;
const fx = new Float32Array(n), fy = new Float32Array(n);
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
const dx = px[j] - px[i], dy = py[j] - py[i];
const d = Math.hypot(dx, dy) || 0.001;
let d2 = d * d; if (d2 < 4) d2 = 4;
const f = repel / d2;
const ux = dx / d, uy = dy / d;
fx[i] -= ux * f; fy[i] -= uy * f;
fx[j] += ux * f; fy[j] += uy * f;
}
}
const cx = W / 2, cy = H / 2;
for (let i = 0; i < n; i++) {
fx[i] += (cx - px[i]) * CENTER_K;
fy[i] += (cy - py[i]) * CENTER_K;
fx[i] += (rand() - 0.5) * speed;
fy[i] += (rand() - 0.5) * speed;
vx[i] = (vx[i] + fx[i] * dt) * DAMP;
vy[i] = (vy[i] + fy[i] * dt) * DAMP;
px[i] += vx[i] * dt; py[i] += vy[i] * dt;
}
// 하드 충돌 해소 — 반지름 합보다 가까운 쌍을 그 자리에서 절반씩 밀어낸다
for (let a = 0; a < n; a++) {
for (let b = a + 1; b < n; b++) {
const ddx = px[b] - px[a], ddy = py[b] - py[a];
const dist = Math.hypot(ddx, ddy) || 0.001;
const minDist = rad[a] + rad[b];
if (dist < minDist) {
const push = (minDist - dist) / 2;
const nx = ddx / dist, ny = ddy / dist;
px[a] -= nx * push; py[a] -= ny * push;
px[b] += nx * push; py[b] += ny * push;
}
}
}
}
function rotateAll(dtheta: number): void {
const px = pxRef.current, py = pyRef.current;
if (!px || !py) return;
const W = wRef.current, H = hRef.current;
const cx = W / 2, cy = H / 2, cs = Math.cos(dtheta), sn = Math.sin(dtheta);
for (let i = 0; i < n; i++) {
const rx = px[i] - cx, ry = py[i] - cy;
px[i] = cx + rx * cs - ry * sn;
py[i] = cy + rx * sn + ry * cs;
}
}
function draw(): void {
const ctx = ctxRef.current;
const col = colRef.current;
const px = pxRef.current, py = pyRef.current, rad = radRef.current;
const W = wRef.current, H = hRef.current;
if (!ctx || !col || !px || !py || !rad) return;
ctx.clearRect(0, 0, W, H);
ctx.fillStyle = "rgb(" + col.panel.join(",") + ")";
ctx.fillRect(0, 0, W, H);
for (let i = 0; i < n; i++) {
ctx.beginPath();
ctx.fillStyle = "rgb(" + col.node.join(",") + ")";
ctx.arc(px[i], py[i], rad[i], 0, Math.PI * 2);
ctx.fill();
ctx.lineWidth = 1;
ctx.strokeStyle = "rgba(" + col.ring.join(",") + ",0.7)";
ctx.stroke();
}
}
function settle(): void {
for (let s = 0; s < 260; s++) step(1 / 60);
draw();
}
let t0 = -1, last = -1;
function frame(now: number): void {
if (t0 < 0) { t0 = now; last = now; }
const dt = Math.min((now - last) / 1000, 0.05); last = now;
step(dt);
rotateAll(OMEGA * dt);
draw();
rafRef.current = requestAnimationFrame(frame);
}
useEffect(() => {
const root = rootRef.current;
const cv = cvRef.current;
if (!root || !cv) return;
colRef.current = {
panel: tokRGB(root, "--gd-panel"),
node: tokRGB(root, "--gd-node"),
ring: tokRGB(root, "--gd-ring")
};
ctxRef.current = cv.getContext("2d");
fit();
function onResize(): void {
fit();
if (reduced()) settle();
}
window.addEventListener("resize", onResize);
if (reduced()) {
settle();
setStill(true);
} else {
t0 = -1; last = -1;
rafRef.current = requestAnimationFrame(frame);
}
return () => {
window.removeEventListener("resize", onResize);
cancelAnimationFrame(rafRef.current);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [n, repel, speed]);
const rootCls = still ? `${styles.root} ${styles.isStill}` : styles.root;
return (
<main className={styles.stage}>
<div
className={rootCls}
ref={rootRef}
style={vars}
role="img"
aria-label={BOARD_LABEL}
tabIndex={0}
>
<canvas className={styles.cv} ref={cvRef}></canvas>
<p className={styles.hint}>
<span className={styles.title}>{HINT_TITLE}</span>
<span className={styles.desc}>{HINT_DESC}</span>
</p>
<div className={styles.bar}>
<span className={styles.meta}>{META_LEFT}</span>
<span className={styles.metaDim}>{META_RIGHT}</span>
</div>
</div>
</main>
);
}04 충돌 방지 — 노드 반지름만큼 서로 밀어내 겹침이 없다 — 측정 누적면적 31.53% · 움직인 프레임 23/23GODRICH 원작 · zip 에 SCSS·React 포함 · 네트워크 그래프 9종 — 힘으로 밀고 당겨 스스로 배치되는 캔버스
이 데모가 속한 글
네트워크 그래프 9종 — 힘으로 밀고 당겨 스스로 배치되는 캔버스네트워크 그래프는 점(노드)과 그 사이를 잇는 선(엣지)으로 관계를 나타낸 그림인데, 이 글은 그 점들의 자리를 사람이 정하지 않고 힘 계산만으로 매 프레임 다시 잡는 캔버스 엔진 아홉 판을 줍니다. 점과 선 몇 개 이 글의 데모 전부 보기

