01긁은 면적을 픽셀로 재 자동으로 벗겨지는 카드
지운 픽셀 수를 실시간으로 세어 절반을 넘으면 나머지 은박이 자동으로 벗겨진다.
쓰임쿠폰 즉시 당첨 확인 카드
clearedPixelRatioSCRATCH_REVEAL_THRESHOLD_PCTautoPeelRemaining
<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">
<div class="scv__prize">
<p class="scv__prizeTitle">20% 할인 쿠폰</p>
<p class="scv__prizeSub">긁어서 결과를 확인하세요</p>
</div>
<canvas class="scv__foil" id="foil" width="280" height="150" aria-hidden="true"></canvas>
</div>
<div class="scv__meter" aria-hidden="true"><div class="scv__meterFill" id="meterFill"></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 *;
// 스크래치 카드 01 — 실제 긁기는 canvas destination-out. 긁힌 알파 픽셀 비율을
// clearedPixelRatio() 로 계산해 SCRATCH_REVEAL_THRESHOLD_PCT 를 넘으면 autoPeelRemaining() 이
// 나머지를 한 번에 지운다. 격자 미리보기(.is-demo)는 같은 함수를 스케줄로 호출한다.
@include stage($stage-ink);
.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-1; font-weight: 800; font-size: 12px; letter-spacing: .04em; }
.scv__zone {
position: relative; border-radius: $r-control; overflow: hidden;
aspect-ratio: 280 / 150; background: $stage-paper;
}
.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;
}
.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%; touch-action: none; }
.scv.is-open .scv__foil { visibility: hidden; }
.scv__meter { margin-top: $sp-1; height: $sp-1; border-radius: $r-pill; background: rgba(255, 255, 255, .28); overflow: hidden; }
.scv__meterFill { height: 100%; width: 0%; background: $subject-cream; border-radius: inherit; }
.scv__reveal {
margin-top: $sp-1; 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-paper; 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; }
.scv__prizeTitle { font-size: 16px; }
}
@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 / 76; }
.scv__meter { margin-top: $sp-1; }
.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: #17141a;
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 4px;
font-weight: 800;
font-size: 12px;
letter-spacing: 0.04em;
}
.scv__zone {
position: relative;
border-radius: 12px;
overflow: hidden;
aspect-ratio: 280/150;
background: #ffffff;
}
.scv__prize {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 4px;
text-align: center;
padding: 8px;
}
.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%;
touch-action: none;
}
.scv.is-open .scv__foil {
visibility: hidden;
}
.scv__meter {
margin-top: 4px;
height: 4px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.28);
overflow: hidden;
}
.scv__meterFill {
height: 100%;
width: 0%;
background: #fff7e6;
border-radius: inherit;
}
.scv__reveal {
margin-top: 4px;
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 #ffffff;
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;
}
.scv__prizeTitle {
font-size: 16px;
}
}
@media (max-height: 220px) {
.stage {
padding: 8px;
}
.scv__card {
padding: 8px 12px;
}
.scv__label {
margin: 0 0 4px;
}
.scv__zone {
aspect-ratio: 280/76;
}
.scv__meter {
margin-top: 4px;
}
.scv__reveal {
margin-top: 4px;
}
.scv__live {
margin-top: 4px;
min-height: 0.9em;
}
}
@media (prefers-reduced-motion: reduce) {
.scv {
cursor: default;
}
}(function () {
// 기법: 긁을 때마다 canvas getImageData 로 지워진 알파 픽셀 수를 세어 전체 대비 비율을
// 계산한다. 그 비율이 SCRATCH_REVEAL_THRESHOLD_PCT 를 넘으면 나머지 은박을 한 번에
// destination-out 으로 지워 자동으로 카드를 연다 — 픽셀 계산 하나가 판정을 만든다.
var root = document.getElementById('scv');
var zone = document.getElementById('zone');
var foil = document.getElementById('foil');
var ctx = foil.getContext('2d');
var meterFill = document.getElementById('meterFill');
var revealBtn = document.getElementById('revealBtn');
var live = document.getElementById('live');
var SCRATCH_REVEAL_THRESHOLD_PCT = 50;
var SCRATCH_BRUSH_R = 15;
var opened = false;
function seedRand(seed) {
var s = seed >>> 0;
return function () { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };
}
var foilRand = seedRand(424011);
function paintFoil() {
ctx.globalCompositeOperation = 'source-over';
ctx.clearRect(0, 0, foil.width, foil.height);
var grad = ctx.createLinearGradient(0, 0, foil.width, foil.height);
grad.addColorStop(0, '#cfd3dd');
grad.addColorStop(.5, '#eef0f5');
grad.addColorStop(1, '#b9bdc9');
ctx.fillStyle = grad;
ctx.fillRect(0, 0, foil.width, foil.height);
ctx.strokeStyle = 'rgba(23,20,26,.16)';
ctx.lineWidth = 1;
for (var i = 0; i < 22; i += 1) {
var x = foilRand() * foil.width, y = foilRand() * foil.height;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + (foilRand() * 22 - 11), 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 clearedPixelRatio() {
var data = ctx.getImageData(0, 0, foil.width, foil.height).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;
}
function updateMeter(ratio) {
meterFill.style.width = Math.round(ratio * 100) + '%';
}
function openCard() {
if (opened) return;
opened = true;
ctx.globalCompositeOperation = 'destination-out';
ctx.fillRect(0, 0, foil.width, foil.height);
updateMeter(1);
root.classList.add('is-open');
live.textContent = '20% 할인 쿠폰이 열렸어요';
}
function autoPeelRemaining(ratio) {
if (ratio * 100 >= SCRATCH_REVEAL_THRESHOLD_PCT) openCard();
}
function pos(e) {
var r = foil.getBoundingClientRect();
return { x: (e.clientX - r.left) * (foil.width / r.width), y: (e.clientY - r.top) * (foil.height / r.height) };
}
paintFoil();
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var dragging = false;
zone.addEventListener('pointerdown', function (e) {
if (opened) return;
root.classList.remove('is-demo');
dragging = true;
var p = pos(e);
scratchAt(p.x, p.y);
var ratio = clearedPixelRatio();
updateMeter(ratio);
autoPeelRemaining(ratio);
if (foil.setPointerCapture) foil.setPointerCapture(e.pointerId);
});
zone.addEventListener('pointermove', function (e) {
if (!dragging || opened) return;
var p = pos(e);
scratchAt(p.x, p.y);
var ratio = clearedPixelRatio();
updateMeter(ratio);
autoPeelRemaining(ratio);
});
window.addEventListener('pointerup', function () { dragging = false; });
revealBtn.addEventListener('click', function () {
root.classList.remove('is-demo');
openCard();
});
// 격자 미리보기 — 드래그 없이 같은 scratchAt·clearedPixelRatio 경로를 스케줄대로 호출한다
var demoRand = seedRand(424012);
var demoPath = [];
(function buildDemoPath() {
var n = 24;
for (var i = 0; i < n; i += 1) {
demoPath.push({
t: 220 + i * 78,
x: (foil.width * 0.16) + (i % 6) * (foil.width * 0.145) + (demoRand() - .5) * 8,
y: (foil.height * 0.26) + Math.floor(i / 6) * (foil.height * 0.24) + (demoRand() - .5) * 8
});
}
})();
var DEMO_LOOP_MS = 3600;
var demoStep = 0;
function resetDemo() {
opened = false;
root.classList.remove('is-open');
paintFoil();
updateMeter(0);
demoStep = 0;
}
function runDemo(tMod) {
while (demoStep < demoPath.length && demoPath[demoStep].t <= tMod) {
var p = demoPath[demoStep];
scratchAt(p.x, p.y);
demoStep += 1;
}
var ratio = clearedPixelRatio();
updateMeter(ratio);
autoPeelRemaining(ratio);
}
if (reduce) root.classList.remove('is-demo');
var elapsed = 0;
var 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);
}
updateMeter(0);
requestAnimationFrame(tick);
})();import { useEffect, useRef } from "react";
import styles from "./ScratchCardRevealPixelThresholdAutopeel.module.scss";
export default function ScratchCardRevealPixelThresholdAutopeel() {
const rootRef = useRef<HTMLDivElement>(null);
const zoneRef = useRef<HTMLDivElement>(null);
const foilRef = useRef<HTMLCanvasElement>(null);
const meterRef = useRef<HTMLDivElement>(null);
const liveRef = useRef<HTMLParagraphElement>(null);
const revealBtnRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
const root = rootRef.current;
const zone = zoneRef.current;
const foil = foilRef.current;
const meterFill = meterRef.current;
const live = liveRef.current;
const revealBtn = revealBtnRef.current;
if (!root || !zone || !foil || !meterFill || !live || !revealBtn) return;
const ctx = foil.getContext("2d");
if (!ctx) return;
const SCRATCH_REVEAL_THRESHOLD_PCT = 50;
const SCRATCH_BRUSH_R = 15;
let opened = false;
function seedRand(seed: number) {
let s = seed >>> 0;
return function () { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };
}
const foilRand = seedRand(424011);
function paintFoil() {
ctx!.globalCompositeOperation = "source-over";
ctx!.clearRect(0, 0, foil!.width, foil!.height);
const grad = ctx!.createLinearGradient(0, 0, foil!.width, foil!.height);
grad.addColorStop(0, "#cfd3dd");
grad.addColorStop(.5, "#eef0f5");
grad.addColorStop(1, "#b9bdc9");
ctx!.fillStyle = grad;
ctx!.fillRect(0, 0, foil!.width, foil!.height);
ctx!.strokeStyle = "rgba(23,20,26,.16)";
ctx!.lineWidth = 1;
for (let i = 0; i < 22; i += 1) {
const x = foilRand() * foil!.width, y = foilRand() * foil!.height;
ctx!.beginPath();
ctx!.moveTo(x, y);
ctx!.lineTo(x + (foilRand() * 22 - 11), 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 clearedPixelRatio() {
const data = ctx!.getImageData(0, 0, foil!.width, foil!.height).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;
}
function updateMeter(ratio: number) {
meterFill!.style.width = Math.round(ratio * 100) + "%";
}
function openCard() {
if (opened) return;
opened = true;
ctx!.globalCompositeOperation = "destination-out";
ctx!.fillRect(0, 0, foil!.width, foil!.height);
updateMeter(1);
root!.classList.add("is-open");
live!.textContent = "20% 할인 쿠폰이 열렸어요";
}
function autoPeelRemaining(ratio: number) {
if (ratio * 100 >= SCRATCH_REVEAL_THRESHOLD_PCT) openCard();
}
function pos(e: PointerEvent) {
const r = foil!.getBoundingClientRect();
return { x: (e.clientX - r.left) * (foil!.width / r.width), y: (e.clientY - r.top) * (foil!.height / r.height) };
}
paintFoil();
const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
let dragging = false;
function onDown(e: PointerEvent) {
if (opened) return;
root!.classList.remove("is-demo");
dragging = true;
const p = pos(e);
scratchAt(p.x, p.y);
const ratio = clearedPixelRatio();
updateMeter(ratio);
autoPeelRemaining(ratio);
foil!.setPointerCapture?.(e.pointerId);
}
function onMove(e: PointerEvent) {
if (!dragging || opened) return;
const p = pos(e);
scratchAt(p.x, p.y);
const ratio = clearedPixelRatio();
updateMeter(ratio);
autoPeelRemaining(ratio);
}
function onUp() { dragging = false; }
zone.addEventListener("pointerdown", onDown);
zone.addEventListener("pointermove", onMove);
window.addEventListener("pointerup", onUp);
function onReveal() {
root!.classList.remove("is-demo");
openCard();
}
revealBtn.addEventListener("click", onReveal);
const demoRand = seedRand(424012);
type DemoPt = { t: number; x: number; y: number };
const demoPath: DemoPt[] = [];
for (let i = 0; i < 24; i += 1) {
demoPath.push({
t: 220 + i * 78,
x: (foil.width * 0.16) + (i % 6) * (foil.width * 0.145) + (demoRand() - .5) * 8,
y: (foil.height * 0.26) + Math.floor(i / 6) * (foil.height * 0.24) + (demoRand() - .5) * 8
});
}
const DEMO_LOOP_MS = 3600;
let demoStep = 0;
function resetDemo() {
opened = false;
root!.classList.remove("is-open");
paintFoil();
updateMeter(0);
demoStep = 0;
}
function runDemo(tMod: number) {
while (demoStep < demoPath.length && demoPath[demoStep].t <= tMod) {
const p = demoPath[demoStep];
scratchAt(p.x, p.y);
demoStep += 1;
}
const ratio = clearedPixelRatio();
updateMeter(ratio);
autoPeelRemaining(ratio);
}
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);
}
updateMeter(0);
raf = requestAnimationFrame(tick);
return () => {
cancelAnimationFrame(raf);
zone.removeEventListener("pointerdown", onDown);
zone.removeEventListener("pointermove", onMove);
window.removeEventListener("pointerup", onUp);
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}>
<div className={styles.scv__prize}>
<p className={styles.scv__prizeTitle}>20% 할인 쿠폰</p>
<p className={styles.scv__prizeSub}>긁어서 결과를 확인하세요</p>
</div>
<canvas className={styles.scv__foil} ref={foilRef} width={280} height={150} aria-hidden="true" />
</div>
<div className={styles.scv__meter} aria-hidden="true"><div className={styles.scv__meterFill} ref={meterRef} /></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>
);
}01 긁은 면적을 픽셀로 재 자동으로 벗겨지는 카드 — 측정 누적면적 12.103% · 움직인 프레임 15/23GODRICH 원작 · zip 에 SCSS·React 포함 · 스크래치 카드 리빌 9가지 — 긁은 면적을 픽셀로 계산하기
이 데모가 속한 글
스크래치 카드 리빌 9가지 — 긁은 면적을 픽셀로 계산하기관찰 기록 09:00 — 손끝이 닿자마자 03번 은박 조각이 중력을 받아 튀어 나간다. 09:04 — 06번 진행 링이 62%에서 멈춰 채워지지 않는다. 09:07 — 09번 화면 속 카드 전부가 한 번에 열린다. 이 글의 데모 전부 보기


