-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwheel.ts
More file actions
303 lines (276 loc) · 11.5 KB
/
Copy pathwheel.ts
File metadata and controls
303 lines (276 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/*
원판(SVG) 렌더링 + 회전 애니메이션 + 결과 연출(하이라이트·틱 사운드).
디자인·효과 규칙은 luckydraw-wheel-design-guide.md 를 따른다:
· 세그먼트 색은 '정보' — 제한 팔레트 4색 교차, 채도색(blue/amber) 인접 금지.
· 입체감은 그림자 없이 프레임 링의 선 두께로.
· 허용 효과: 스핀 감속 1회, 틱 사운드, 당첨 하이라이트. 그 외 장식 모션 금지.
각도 규약: 모든 각도는 12시(포인터 위치)에서 '시계방향'으로 잰다.
· 슬롯 i 는 [i·seg, (i+1)·seg) 를 차지하고, 중심각은 (i+0.5)·seg.
· 로터를 R 만큼 시계방향으로 돌리면, 원래 각도 a 의 점은 a+R 로 이동한다.
· 슬롯 i 를 포인터(0°)에 맞추려면 R ≡ -(i+0.5)·seg (mod 360).
→ 결과 슬롯을 '먼저' 정하고 R 을 역산한다(FR-3.3).
*/
const VIEW = 100;
const CENTER = VIEW / 2;
const RADIUS = 46; // 섹터 반지름(프레임 링 안쪽)
const RIM_RADIUS = 47.5; // 프레임 링 중심 반지름 (바깥 끝 49)
const RIM_WIDTH = 3; // 입체감은 그림자 대신 링 두께로(guide 3.2)
const HUB_RADIUS = 10;
const LABEL_IN = HUB_RADIUS + 3; // 라벨이 쓸 수 있는 반경 구간
const LABEL_OUT = RADIUS - 3;
const LABEL_SPAN = LABEL_OUT - LABEL_IN;
const FONT_MIN = 2.6; // viewBox 단위(100 기준). 이보다 작아지면 라벨을 자른다.
const FONT_MAX = 6.5;
const SPIN_DURATION_MS = 5000;
const SPIN_DURATION_REDUCED_MS = 500;
const SPIN_EASING = "cubic-bezier(0.12, 0, 0.05, 1)"; // 감속 1회(guide 4.1)
const FULL_SPINS = 5;
/* 세그먼트 팔레트 — 라이트 파스텔 계열(저채도, 눈에 편함). 라벨은 진한 무채색으로 대비 확보. */
const SEG_COLORS = ["#bfdbfe", "#ffffff", "#fde68a", "#e7e5e4"];
const SEG_LABEL_COLOR = "#1a1a1a";
const MISS_COLOR = "#6f6f6f"; // 꽝 = 무채색. 색만이 아니라 라벨("꽝")로도 구분.
const FRAME_COLOR = "#1a1a1a";
const WIN_COLOR = "#16a34a"; // 당첨 하이라이트 — 결과 시점에만 사용
export interface SectorView {
kind: "prize" | "miss";
/** 섹터에 표시할 문자열(경품명 또는 번호, 또는 "꽝"). ui.ts 가 해석해 넘긴다. */
label: string;
}
/** 12시 기준 시계방향 각도(deg)를 SVG 좌표점으로 변환. */
function pointOnCircle(deg: number, r: number): { x: number; y: number } {
const rad = (deg * Math.PI) / 180;
return {
x: CENTER + r * Math.sin(rad),
y: CENTER - r * Math.cos(rad),
};
}
/** a0→a1(시계방향) 부채꼴 path. */
function sectorPath(a0: number, a1: number): string {
const p0 = pointOnCircle(a0, RADIUS);
const p1 = pointOnCircle(a1, RADIUS);
const largeArc = a1 - a0 > 180 ? 1 : 0;
return [
`M ${CENTER} ${CENTER}`,
`L ${p0.x.toFixed(3)} ${p0.y.toFixed(3)}`,
`A ${RADIUS} ${RADIUS} 0 ${largeArc} 1 ${p1.x.toFixed(3)} ${p1.y.toFixed(3)}`,
"Z",
].join(" ");
}
function escapeXml(s: string): string {
return s
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}
/** 문자 폭 근사(em) — 한글/CJK ≈ 1em, 라틴/숫자 ≈ 0.62em. 측정 API 없이 충분한 정밀도. */
function charWidthEm(ch: string): number {
return (ch.codePointAt(0) ?? 0) > 0x2e80 ? 1 : 0.62;
}
function estWidthEm(s: string): number {
let w = 0;
for (const ch of s) w += charWidthEm(ch);
return w;
}
/**
* 라벨이 반경 구간(LABEL_SPAN)과 섹터 폭 안에 들어가도록 폰트 크기를 정한다.
* 글자 수가 많을수록 크기가 줄고, 최소 크기로도 넘치면 잘라서 "…"을 붙인다(EC-8).
*/
function fitLabel(label: string, seg: number): { text: string; size: number } {
// 라벨 안쪽 끝에서의 현(chord) — 글자 높이(≈1em)가 섹터 폭을 넘지 않게 제한.
const chord = 2 * LABEL_IN * Math.sin((Math.min(seg, 180) * Math.PI) / 360);
const maxSize = Math.min(FONT_MAX, chord * 0.8);
let text = label;
let size = Math.min(maxSize, LABEL_SPAN / Math.max(estWidthEm(text), 0.62));
if (size < FONT_MIN) {
size = Math.min(FONT_MIN, maxSize);
// 최소 크기로도 반경 구간을 넘칠 때만 자른다(짧은 라벨은 그대로).
if (estWidthEm(text) * size > LABEL_SPAN) {
const maxEm = LABEL_SPAN / size - 0.62; // "…" 자리를 빼고 자른다
let w = 0;
let cut = 0;
for (const ch of text) {
if (w + charWidthEm(ch) > maxEm) break;
w += charWidthEm(ch);
cut++;
}
text = [...text].slice(0, cut).join("") + "…";
}
}
return { text, size };
}
/**
* 원판 전체 마크업을 문자열로 반환.
* .wheel-rotor <g> 안에 섹터+라벨이 들어가고, 포인터·링·허브는 회전하지 않도록 바깥에 둔다.
* 라벨은 반지름 방향으로 회전 배치 — 긴 경품명도 반경 구간을 따라 눕는다.
*/
export function renderWheelSVG(sectors: SectorView[]): string {
const n = sectors.length;
const seg = 360 / n;
const parts = sectors.map((s, i) => {
let fill: string;
let labelFill: string;
if (s.kind === "miss") {
fill = MISS_COLOR;
labelFill = "#ffffff";
} else {
let c = i % 4;
// 슬롯 수가 홀수면 마지막 칸이 첫 칸과 같은 색으로 맞닿으므로 중립색으로 강제.
if (i === n - 1 && n % 2 === 1) c = 3;
fill = SEG_COLORS[c]!;
labelFill = SEG_LABEL_COLOR;
}
const a0 = i * seg;
const a1 = (i + 1) * seg;
const center = (i + 0.5) * seg;
const { text, size } = fitLabel(s.label, seg);
const lp = pointOnCircle(center, (LABEL_IN + LABEL_OUT) / 2);
const x = lp.x.toFixed(2);
const y = lp.y.toFixed(2);
return `
<path data-slot="${i}" d="${sectorPath(a0, a1)}" fill="${fill}"
stroke="${FRAME_COLOR}" stroke-width="0.35" />
<text data-slot="${i}" class="sector-label" x="${x}" y="${y}"
transform="rotate(${(center - 90).toFixed(2)} ${x} ${y})"
text-anchor="middle" dominant-baseline="central"
font-size="${size.toFixed(2)}" font-weight="700"
fill="${labelFill}">${escapeXml(text)}</text>`;
});
return `
<div class="wheel-wrap">
<div class="wheel-pointer" aria-hidden="true"></div>
<svg class="wheel" viewBox="0 0 ${VIEW} ${VIEW}" role="img" aria-label="추첨 원판">
<g class="wheel-rotor" data-rotation="0">
${parts.join("")}
</g>
<circle cx="${CENTER}" cy="${CENTER}" r="${RIM_RADIUS}" fill="none"
stroke="${FRAME_COLOR}" stroke-width="${RIM_WIDTH}" />
<g class="wheel-hub" role="button" tabindex="0" aria-label="원판 돌리기">
<circle cx="${CENTER}" cy="${CENTER}" r="${HUB_RADIUS}" fill="${FRAME_COLOR}" />
<text x="${CENTER}" y="${CENTER}" text-anchor="middle" dominant-baseline="central"
fill="#ffffff" font-size="4" font-weight="700" letter-spacing="0.4">SPIN</text>
</g>
</svg>
</div>`;
}
/**
* 결과 연출(guide 4.1) — 당첨 섹터를 초록으로 지목하고 나머지는 가라앉힌다.
* 직후 전체 재렌더가 원판을 다시 그리므로 되돌리기는 필요 없다.
*/
export function highlightResult(rotor: SVGGElement, slotIndex: number, isWin: boolean): void {
rotor.querySelectorAll<SVGElement>("[data-slot]").forEach((el) => {
if (Number(el.dataset.slot) === slotIndex) {
if (isWin) el.setAttribute("fill", el.tagName === "text" ? "#ffffff" : WIN_COLOR);
} else {
el.setAttribute("opacity", "0.3");
}
});
}
/* ── 틱 사운드 — Web Audio 단발 oscillator(파일 불필요, guide 4.1) ── */
let audioCtx: AudioContext | null = null;
function ensureAudio(): void {
try {
audioCtx ??= new AudioContext();
if (audioCtx.state === "suspended") void audioCtx.resume();
} catch {
audioCtx = null; // 사운드는 부가 연출 — 실패해도 추첨은 계속된다.
}
}
function tick(): void {
if (!audioCtx) return;
const t = audioCtx.currentTime;
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.frequency.value = 900;
gain.gain.setValueAtTime(0.15, t);
gain.gain.exponentialRampToValueAtTime(0.001, t + 0.05);
osc.connect(gain).connect(audioCtx.destination);
osc.start(t);
osc.stop(t + 0.05);
}
/** 현재 CSS transform 의 회전각(deg). transition 진행 중의 실제 값을 읽는다. */
function currentRotation(el: Element): number {
const t = getComputedStyle(el).transform;
if (!t || t === "none") return 0;
const m = new DOMMatrixReadOnly(t);
return (Math.atan2(m.b, m.a) * 180) / Math.PI;
}
/**
* 회전 중 포인터가 섹터 경계를 지날 때마다 틱.
* 베지어를 수식으로 풀지 않고 매 프레임 실제 회전각을 읽으므로 감속과 정확히 동기화된다.
* 빠른 구간은 프레임당 1회로 자연히 뭉개지고, 감속하면 틱 간격이 벌어진다.
*/
function startTicks(rotor: SVGGElement, seg: number): () => void {
let prev = currentRotation(rotor);
let acc = 0;
let raf = requestAnimationFrame(function step() {
const cur = currentRotation(rotor);
let d = (cur - prev) % 360;
if (d < 0) d += 360;
acc += d;
prev = cur;
if (acc >= seg) {
acc %= seg;
tick();
}
raf = requestAnimationFrame(step);
});
return () => cancelAnimationFrame(raf);
}
function prefersReducedMotion(): boolean {
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
/**
* 결과 슬롯 인덱스로 회전을 역산해 애니메이션한다.
* 결과는 호출 전 이미 결정돼 있고(FR-3.3), 이 함수는 '그 섹터에 멈추도록' 각도만 맞춘다.
* transitionend 시 resolve. 누적 회전값(dataset.rotation)으로 항상 앞으로만 돌린다.
*/
export function spinTo(
rotor: SVGGElement,
slotIndex: number,
slotCount: number,
rng: () => number = Math.random
): Promise<void> {
const seg = 360 / slotCount;
// 섹터 중앙에서 살짝 벗어나 멈추도록 지터를 더하되, 슬롯 경계는 넘지 않는다.
const jitter = (rng() - 0.5) * seg * 0.6;
const targetCenter = (slotIndex + 0.5) * seg;
const desiredMod = (((-(targetCenter + jitter)) % 360) + 360) % 360;
const current = parseFloat(rotor.dataset.rotation || "0");
const currentMod = ((current % 360) + 360) % 360;
let delta = desiredMod - currentMod;
if (delta < 0) delta += 360;
const reduced = prefersReducedMotion();
const spins = reduced ? 0 : FULL_SPINS;
const duration = reduced ? SPIN_DURATION_REDUCED_MS : SPIN_DURATION_MS;
const final = current + spins * 360 + delta;
rotor.dataset.rotation = String(final);
let stopTicks: (() => void) | null = null;
if (!reduced) {
ensureAudio();
stopTicks = startTicks(rotor, seg);
}
return new Promise<void>((resolve) => {
let done = false;
const finish = () => {
if (done) return;
done = true;
stopTicks?.();
rotor.removeEventListener("transitionend", onEnd);
resolve();
};
const onEnd = (e: TransitionEvent) => {
if (e.propertyName === "transform") finish();
};
rotor.addEventListener("transitionend", onEnd);
// 안전망: transitionend 미발화 환경 대비 타임아웃.
window.setTimeout(finish, duration + 200);
// transition 을 먼저 적용한 뒤 다음 프레임에 transform 을 바꿔 애니메이션을 보장.
rotor.style.transition = `transform ${duration}ms ${SPIN_EASING}`;
requestAnimationFrame(() => {
requestAnimationFrame(() => {
rotor.style.transform = `rotate(${final}deg)`;
});
});
});
}