08방향키로도 같은 결과를 여는 대체 경로
드래그 없이 방향키나 버튼을 누르면 같은 픽셀 계산 경로를 그대로 밟아 카드가 열린다.
쓰임키보드 전용 접근성 경로
placeCursorKEY_STEPcursor

<main class="stage">
<div class="scv is-demo" id="scv">
<div class="scv__card">
<p class="scv__label">스크래치 카드</p>
<div class="scv__zone" id="zone" tabindex="0" role="application" aria-label="스크래치 카드, 방향키로 이동 후 스페이스로 긁기">
<div class="scv__prize">
<p class="scv__prizeTitle">배송비 쿠폰</p>
<p class="scv__prizeSub">방향키 + 스페이스로도 긁을 수 있어요</p>
</div>
<canvas class="scv__foil" id="foil" width="280" height="150" aria-hidden="true"></canvas>
<div class="scv__cursor" id="cursor" aria-hidden="true"></div>
</div>
<button type="button" class="scv__reveal" id="revealBtn">한 번에 보기</button>
<p class="scv__live" id="live" aria-live="polite"></p>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 스크래치 카드 08 — 키보드 커서(cursor.x/y)와 포인터가 같은 scratchAt()/clearedRatio() 를
// 호출한다. 방향키로 이동(state 변화) + Enter/Space 로 긁기, 전부 preventDefault 처리.
@include stage($stage-paper);
.scv { display: flex; justify-content: center; width: 100%; }
.scv__card {
width: min(100%, 300px); background: $subject-blue-deep; color: $subject-cream;
border-radius: $r-card; box-shadow: $shadow-raised; padding: $sp-4;
}
.scv__label { margin: 0 0 $sp-2; font-weight: 800; font-size: 12px; letter-spacing: .04em; }
.scv__zone {
position: relative; border-radius: $r-control; overflow: hidden;
aspect-ratio: 280 / 150; background: #eef0f3; touch-action: none;
}
.scv__zone:focus-visible { outline: 3px solid $subject-cream; outline-offset: 2px; }
.scv__prize {
position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center;
justify-content: center; gap: $sp-1; text-align: center; padding: $sp-2; z-index: 0;
}
.scv__prizeTitle { margin: 0; font-weight: 800; font-size: clamp(18px, 6vw, 22px); color: $subject-blue-deep; }
.scv__prizeSub { margin: 0; font-weight: 700; font-size: 11px; color: rgba(23, 20, 26, .68); }
.scv__foil { position: absolute; inset: 0; width: 100%; height: 100%; z-index: 1; }
.scv.is-open .scv__foil { visibility: hidden; }
.scv__cursor {
position: absolute; width: 18px; height: 18px; margin: -9px 0 0 -9px;
border: 2px solid $stage-ink; border-radius: 50%; z-index: 2; pointer-events: none;
box-shadow: 0 0 0 2px rgba(255, 255, 255, .8);
}
.scv.is-open .scv__cursor { display: none; }
.scv__reveal {
margin-top: $sp-2; border: 0; cursor: pointer; background: $subject-cream; color: $subject-blue-deep;
border-radius: $r-pill; font-family: inherit; font-weight: 800; font-size: 11px; padding: $sp-1 $sp-3; line-height: 1.3;
}
.scv__reveal:focus-visible { outline: 3px solid $stage-ink; outline-offset: 2px; }
.scv__live { margin: $sp-1 0 0; min-height: 1em; font-weight: 700; font-size: 10px; color: $subject-cream; }
@media (max-width: 340px) {
.scv__card { padding: $sp-3; }
}
@media (max-height: 220px) {
.stage { padding: $sp-2; }
.scv__card { padding: $sp-2 $sp-3; }
.scv__label { margin: 0 0 $sp-1; }
.scv__zone { aspect-ratio: 280 / 88; }
.scv__reveal { margin-top: $sp-1; }
.scv__live { margin-top: $sp-1; min-height: .9em; }
}
@media (prefers-reduced-motion: reduce) {
.scv { cursor: default; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #ffffff;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.scv {
display: flex;
justify-content: center;
width: 100%;
}
.scv__card {
width: min(100%, 300px);
background: #0a4fe8;
color: #fff7e6;
border-radius: 16px;
box-shadow: 0 14px 24px rgba(23, 20, 26, 0.32);
padding: 16px;
}
.scv__label {
margin: 0 0 8px;
font-weight: 800;
font-size: 12px;
letter-spacing: 0.04em;
}
.scv__zone {
position: relative;
border-radius: 12px;
overflow: hidden;
aspect-ratio: 280/150;
background: #eef0f3;
touch-action: none;
}
.scv__zone:focus-visible {
outline: 3px solid #fff7e6;
outline-offset: 2px;
}
.scv__prize {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 4px;
text-align: center;
padding: 8px;
z-index: 0;
}
.scv__prizeTitle {
margin: 0;
font-weight: 800;
font-size: clamp(18px, 6vw, 22px);
color: #0a4fe8;
}
.scv__prizeSub {
margin: 0;
font-weight: 700;
font-size: 11px;
color: rgba(23, 20, 26, 0.68);
}
.scv__foil {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
z-index: 1;
}
.scv.is-open .scv__foil {
visibility: hidden;
}
.scv__cursor {
position: absolute;
width: 18px;
height: 18px;
margin: -9px 0 0 -9px;
border: 2px solid #17141a;
border-radius: 50%;
z-index: 2;
pointer-events: none;
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.8);
}
.scv.is-open .scv__cursor {
display: none;
}
.scv__reveal {
margin-top: 8px;
border: 0;
cursor: pointer;
background: #fff7e6;
color: #0a4fe8;
border-radius: 999px;
font-family: inherit;
font-weight: 800;
font-size: 11px;
padding: 4px 12px;
line-height: 1.3;
}
.scv__reveal:focus-visible {
outline: 3px solid #17141a;
outline-offset: 2px;
}
.scv__live {
margin: 4px 0 0;
min-height: 1em;
font-weight: 700;
font-size: 10px;
color: #fff7e6;
}
@media (max-width: 340px) {
.scv__card {
padding: 12px;
}
}
@media (max-height: 220px) {
.stage {
padding: 8px;
}
.scv__card {
padding: 8px 12px;
}
.scv__label {
margin: 0 0 4px;
}
.scv__zone {
aspect-ratio: 280/88;
}
.scv__reveal {
margin-top: 4px;
}
.scv__live {
margin-top: 4px;
min-height: 0.9em;
}
}
@media (prefers-reduced-motion: reduce) {
.scv {
cursor: default;
}
}(function () {
// 기법: 키보드로 이동하는 가상 커서(cursorX, cursorY)를 두고 Enter/Space 가 포인터 드래그와
// 완전히 같은 scratchAt()/clearedRatio() 경로를 호출한다 — 별도의 "키보드용 처리"가 없다.
var root = document.getElementById('scv');
var zone = document.getElementById('zone');
var foil = document.getElementById('foil');
var ctx = foil.getContext('2d');
var cursorEl = document.getElementById('cursor');
var revealBtn = document.getElementById('revealBtn');
var live = document.getElementById('live');
var FW = foil.width, FH = foil.height;
var SCRATCH_BRUSH_R = 16;
var KEY_STEP = 22;
function seedRand(seed) {
var s = seed >>> 0;
return function () { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };
}
var foilRand = seedRand(424081);
function paintFoil() {
ctx.globalCompositeOperation = 'source-over';
ctx.clearRect(0, 0, FW, FH);
var grad = ctx.createLinearGradient(0, 0, FW, FH);
grad.addColorStop(0, '#dfe3ea');
grad.addColorStop(.5, '#f4f6f9');
grad.addColorStop(1, '#c9ced8');
ctx.fillStyle = grad;
ctx.fillRect(0, 0, FW, FH);
ctx.strokeStyle = 'rgba(23,20,26,.14)';
ctx.lineWidth = 1;
for (var i = 0; i < 18; i += 1) {
var x = foilRand() * FW, y = foilRand() * FH;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + (foilRand() * 20 - 10), y + (foilRand() * 8 - 4));
ctx.stroke();
}
}
// 실제 긁기 경로 — 포인터도 키보드도 이 함수 하나만 호출한다
function scratchAt(x, y) {
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(x, y, SCRATCH_BRUSH_R, 0, Math.PI * 2);
ctx.fill();
}
function clearedRatio() {
var data = ctx.getImageData(0, 0, FW, FH).data;
var clear = 0, total = data.length / 4;
for (var i = 3; i < data.length; i += 4) { if (data[i] < 40) clear += 1; }
return clear / total;
}
var opened = false;
function openCard() {
if (opened) return;
opened = true;
ctx.globalCompositeOperation = 'destination-out';
ctx.fillRect(0, 0, FW, FH);
root.classList.add('is-open');
live.textContent = '배송비 쿠폰이 열렸어요';
}
function pos(e) {
var r = foil.getBoundingClientRect();
return { x: (e.clientX - r.left) * (FW / r.width), y: (e.clientY - r.top) * (FH / r.height) };
}
paintFoil();
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var dragging = false;
var cursor = { x: FW / 2, y: FH / 2 };
function placeCursor() {
var r = foil.getBoundingClientRect();
var scaleX = r.width / FW, scaleY = r.height / FH;
cursorEl.style.left = (cursor.x * scaleX) + 'px';
cursorEl.style.top = (cursor.y * scaleY) + 'px';
}
zone.addEventListener('pointerdown', function (e) {
if (opened) return;
root.classList.remove('is-demo');
dragging = true;
var p = pos(e);
cursor.x = p.x; cursor.y = p.y;
scratchAt(p.x, p.y);
placeCursor();
if (clearedRatio() > .82) openCard();
if (zone.setPointerCapture) zone.setPointerCapture(e.pointerId);
});
zone.addEventListener('pointermove', function (e) {
if (!dragging || opened) return;
var p = pos(e);
cursor.x = p.x; cursor.y = p.y;
scratchAt(p.x, p.y);
placeCursor();
if (clearedRatio() > .82) openCard();
});
window.addEventListener('pointerup', function () { dragging = false; });
// 키보드 경로 — 빈 핸들러 없음. 실제로 커서를 옮기고(state 변화) preventDefault 로 스크롤을 막는다.
zone.addEventListener('keydown', function (e) {
if (opened) return;
var moved = false;
if (e.key === 'ArrowUp') { cursor.y = Math.max(6, cursor.y - KEY_STEP); moved = true; }
else if (e.key === 'ArrowDown') { cursor.y = Math.min(FH - 6, cursor.y + KEY_STEP); moved = true; }
else if (e.key === 'ArrowLeft') { cursor.x = Math.max(6, cursor.x - KEY_STEP); moved = true; }
else if (e.key === 'ArrowRight') { cursor.x = Math.min(FW - 6, cursor.x + KEY_STEP); moved = true; }
else if (e.key === 'Enter' || e.key === ' ') {
root.classList.remove('is-demo');
scratchAt(cursor.x, cursor.y);
var ratio = clearedRatio();
live.textContent = Math.round(ratio * 100) + '% 긁었어요';
if (ratio > .82) openCard();
e.preventDefault();
return;
} else { return; }
root.classList.remove('is-demo');
placeCursor();
e.preventDefault();
});
revealBtn.addEventListener('click', function () { root.classList.remove('is-demo'); openCard(); });
// 자동 재생도 같은 scratchAt() 를 호출 — 키보드 시뮬레이션과 같은 경로
var demoRand = seedRand(424082);
var demoPath = [];
(function buildDemoPath() {
for (var i = 0; i < 20; i += 1) {
demoPath.push({
t: 220 + i * 90,
x: (FW * 0.14) + (i % 5) * (FW * 0.18) + (demoRand() - .5) * 6,
y: (FH * 0.22) + Math.floor(i / 5) * (FH * 0.28) + (demoRand() - .5) * 6
});
}
})();
var DEMO_LOOP_MS = 3800;
var demoStep = 0;
function resetDemo() {
opened = false;
root.classList.remove('is-open');
paintFoil();
demoStep = 0;
}
function runDemo(tMod) {
while (demoStep < demoPath.length && demoPath[demoStep].t <= tMod) {
var p = demoPath[demoStep];
cursor.x = p.x; cursor.y = p.y;
scratchAt(p.x, p.y);
placeCursor();
demoStep += 1;
if (clearedRatio() > .82) openCard();
}
}
placeCursor();
if (reduce) root.classList.remove('is-demo');
var elapsed = 0, lastTs = null;
function tick(ts) {
if (lastTs === null) lastTs = ts;
var dt = Math.min(ts - lastTs, 48);
lastTs = ts;
if (!reduce && root.classList.contains('is-demo')) {
elapsed += dt;
var tMod = elapsed % DEMO_LOOP_MS;
if (tMod < dt) resetDemo();
runDemo(tMod);
}
requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
})();import { useEffect, useRef } from "react";
import styles from "./ScratchCardRevealKeyboardFallback.module.scss";
export default function ScratchCardRevealKeyboardFallback() {
const rootRef = useRef<HTMLDivElement>(null);
const zoneRef = useRef<HTMLDivElement>(null);
const foilRef = useRef<HTMLCanvasElement>(null);
const cursorRef = useRef<HTMLDivElement>(null);
const revealBtnRef = useRef<HTMLButtonElement>(null);
const liveRef = useRef<HTMLParagraphElement>(null);
useEffect(() => {
const root = rootRef.current;
const zone = zoneRef.current;
const foil = foilRef.current;
const cursorEl = cursorRef.current;
const revealBtn = revealBtnRef.current;
const live = liveRef.current;
if (!root || !zone || !foil || !cursorEl || !revealBtn || !live) return;
const ctx = foil.getContext("2d");
if (!ctx) return;
const FW = foil.width, FH = foil.height;
const SCRATCH_BRUSH_R = 16;
const KEY_STEP = 22;
function seedRand(seed: number) {
let s = seed >>> 0;
return function () { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };
}
const foilRand = seedRand(424081);
function paintFoil() {
ctx!.globalCompositeOperation = "source-over";
ctx!.clearRect(0, 0, FW, FH);
const grad = ctx!.createLinearGradient(0, 0, FW, FH);
grad.addColorStop(0, "#dfe3ea");
grad.addColorStop(.5, "#f4f6f9");
grad.addColorStop(1, "#c9ced8");
ctx!.fillStyle = grad;
ctx!.fillRect(0, 0, FW, FH);
ctx!.strokeStyle = "rgba(23,20,26,.14)";
ctx!.lineWidth = 1;
for (let i = 0; i < 18; i += 1) {
const x = foilRand() * FW, y = foilRand() * FH;
ctx!.beginPath();
ctx!.moveTo(x, y);
ctx!.lineTo(x + (foilRand() * 20 - 10), y + (foilRand() * 8 - 4));
ctx!.stroke();
}
}
function scratchAt(x: number, y: number) {
ctx!.globalCompositeOperation = "destination-out";
ctx!.beginPath();
ctx!.arc(x, y, SCRATCH_BRUSH_R, 0, Math.PI * 2);
ctx!.fill();
}
function clearedRatio() {
const data = ctx!.getImageData(0, 0, FW, FH).data;
let clear = 0;
const total = data.length / 4;
for (let i = 3; i < data.length; i += 4) { if (data[i] < 40) clear += 1; }
return clear / total;
}
let opened = false;
function openCard() {
if (opened) return;
opened = true;
ctx!.globalCompositeOperation = "destination-out";
ctx!.fillRect(0, 0, FW, FH);
root!.classList.add("is-open");
live!.textContent = "배송비 쿠폰이 열렸어요";
}
function pos(e: PointerEvent) {
const r = foil!.getBoundingClientRect();
return { x: (e.clientX - r.left) * (FW / r.width), y: (e.clientY - r.top) * (FH / r.height) };
}
paintFoil();
const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
let dragging = false;
const cursor = { x: FW / 2, y: FH / 2 };
function placeCursor() {
const r = foil!.getBoundingClientRect();
const scaleX = r.width / FW, scaleY = r.height / FH;
cursorEl!.style.left = (cursor.x * scaleX) + "px";
cursorEl!.style.top = (cursor.y * scaleY) + "px";
}
function onDown(e: PointerEvent) {
if (opened) return;
root!.classList.remove("is-demo");
dragging = true;
const p = pos(e);
cursor.x = p.x; cursor.y = p.y;
scratchAt(p.x, p.y);
placeCursor();
if (clearedRatio() > .82) openCard();
zone!.setPointerCapture?.(e.pointerId);
}
function onMove(e: PointerEvent) {
if (!dragging || opened) return;
const p = pos(e);
cursor.x = p.x; cursor.y = p.y;
scratchAt(p.x, p.y);
placeCursor();
if (clearedRatio() > .82) openCard();
}
function onUp() { dragging = false; }
zone.addEventListener("pointerdown", onDown);
zone.addEventListener("pointermove", onMove);
window.addEventListener("pointerup", onUp);
function onKeydown(e: KeyboardEvent) {
if (opened) return;
let moved = false;
if (e.key === "ArrowUp") { cursor.y = Math.max(6, cursor.y - KEY_STEP); moved = true; }
else if (e.key === "ArrowDown") { cursor.y = Math.min(FH - 6, cursor.y + KEY_STEP); moved = true; }
else if (e.key === "ArrowLeft") { cursor.x = Math.max(6, cursor.x - KEY_STEP); moved = true; }
else if (e.key === "ArrowRight") { cursor.x = Math.min(FW - 6, cursor.x + KEY_STEP); moved = true; }
else if (e.key === "Enter" || e.key === " ") {
root!.classList.remove("is-demo");
scratchAt(cursor.x, cursor.y);
const ratio = clearedRatio();
live!.textContent = Math.round(ratio * 100) + "% 긁었어요";
if (ratio > .82) openCard();
e.preventDefault();
return;
} else { return; }
if (!moved) return;
root!.classList.remove("is-demo");
placeCursor();
e.preventDefault();
}
zone.addEventListener("keydown", onKeydown);
function onReveal() { root!.classList.remove("is-demo"); openCard(); }
revealBtn.addEventListener("click", onReveal);
const demoRand = seedRand(424082);
type DemoPt = { t: number; x: number; y: number };
const demoPath: DemoPt[] = [];
for (let i = 0; i < 20; i += 1) {
demoPath.push({
t: 220 + i * 90,
x: (FW * 0.14) + (i % 5) * (FW * 0.18) + (demoRand() - .5) * 6,
y: (FH * 0.22) + Math.floor(i / 5) * (FH * 0.28) + (demoRand() - .5) * 6
});
}
const DEMO_LOOP_MS = 3800;
let demoStep = 0;
function resetDemo() {
opened = false;
root!.classList.remove("is-open");
paintFoil();
demoStep = 0;
}
function runDemo(tMod: number) {
while (demoStep < demoPath.length && demoPath[demoStep].t <= tMod) {
const p = demoPath[demoStep];
cursor.x = p.x; cursor.y = p.y;
scratchAt(p.x, p.y);
placeCursor();
demoStep += 1;
if (clearedRatio() > .82) openCard();
}
}
placeCursor();
if (reduce) root.classList.remove("is-demo");
let elapsed = 0;
let lastTs: number | null = null;
let raf = 0;
function tick(ts: number) {
if (lastTs === null) lastTs = ts;
const dt = Math.min(ts - lastTs, 48);
lastTs = ts;
if (!reduce && root!.classList.contains("is-demo")) {
elapsed += dt;
const tMod = elapsed % DEMO_LOOP_MS;
if (tMod < dt) resetDemo();
runDemo(tMod);
}
raf = requestAnimationFrame(tick);
}
raf = requestAnimationFrame(tick);
return () => {
cancelAnimationFrame(raf);
zone.removeEventListener("pointerdown", onDown);
zone.removeEventListener("pointermove", onMove);
window.removeEventListener("pointerup", onUp);
zone.removeEventListener("keydown", onKeydown);
revealBtn.removeEventListener("click", onReveal);
};
}, []);
return (
<main className={styles.stage}>
<div className={`${styles.scv} is-demo`} ref={rootRef}>
<div className={styles.scv__card}>
<p className={styles.scv__label}>스크래치 카드</p>
<div
className={styles.scv__zone}
ref={zoneRef}
tabIndex={0}
role="application"
aria-label="스크래치 카드, 방향키로 이동 후 스페이스로 긁기"
>
<div className={styles.scv__prize}>
<p className={styles.scv__prizeTitle}>배송비 쿠폰</p>
<p className={styles.scv__prizeSub}>방향키 + 스페이스로도 긁을 수 있어요</p>
</div>
<canvas className={styles.scv__foil} ref={foilRef} width={280} height={150} aria-hidden="true" />
<div className={styles.scv__cursor} ref={cursorRef} aria-hidden="true" />
</div>
<button type="button" className={styles.scv__reveal} ref={revealBtnRef}>한 번에 보기</button>
<p className={styles.scv__live} ref={liveRef} aria-live="polite"></p>
</div>
</div>
</main>
);
}08 방향키로도 같은 결과를 여는 대체 경로 — 측정 누적면적 4.137% · 움직인 프레임 15/23GODRICH 원작 · zip 에 SCSS·React 포함 · 스크래치 카드 리빌 9가지 — 긁은 면적을 픽셀로 계산하기
이 데모가 속한 글
스크래치 카드 리빌 9가지 — 긁은 면적을 픽셀로 계산하기관찰 기록 09:00 — 손끝이 닿자마자 03번 은박 조각이 중력을 받아 튀어 나간다. 09:04 — 06번 진행 링이 62%에서 멈춰 채워지지 않는다. 09:07 — 09번 화면 속 카드 전부가 한 번에 열린다. 이 글의 데모 전부 보기


