Scratch-to-Reveal Lucky Bag — Rub the Foil to Show Five Items and the Bag Price
A scratch-card style block for New Year lucky-bag (fukubukuro) product pages. A silver foil drawn on canvas covers five items (icon, name, list price) and their total; rubbing with a finger or mouse scratches it away. The scratched area is counted on an 8px grid, and past 60% the rest of the foil melts away in 300ms and a band shows "Total list price ¥12,000 → Lucky bag ¥5,500" with the saving. The contents are fixed (no lottery). A "Rub to see inside" hint and a "Show all" button sit on the foil, and Enter scratches one row at a time from the keyboard. Item names stay in the DOM, so screen readers can read them under the foil. A collapsed panel edits the five items, the bag price and the foil color (silver, gold, vermilion), and tabs copy the result as React (TSX) or dependency-free HTML+JS. It can also export a 1200×630 share image of the half-scratched card with the price masked. Reduced motion skips the melt. No dependencies.
Preview
福袋の中身を、
銀色の膜を指やマウスでこすると、中身5品と福袋の価格が出ます。中身は毎回同じで、抽選はしません。
初売りの福袋
中身5品・中身は全員同じです
- 白磁のマグカップ¥2,800
- 綿のフェイスタオル 2枚¥2,200
- 帆布のトートバッグ¥3,300
- ほうじ茶 ティーバッグ 20包¥1,500
- 木の箸と箸置き¥2,200
- 中身の定価合計¥12,000
こすった量0%
60%までこすると、残りが溶けて福袋の価格が出ます
中身の定価合計¥12,000から福袋¥5,500
お得6,500円分おトク(定価合計の46%の価格)
中身・価格・膜の色を変える
変えた中身・価格・色は、カードと下のコードの両方に入ります。
このカードのコードをコピー(React・HTML+JS)
"use client";
import { useEffect, useRef, useState, type PointerEvent } from "react";
// 福袋の中身をこすって見せる(依存なし・React + Tailwind CSS v4)
const ITEMS = [
{ name: "白磁のマグカップ", price: 2800, d: "M5 8h11v7a4 4 0 0 1-4 4H9a4 4 0 0 1-4-4z M16 10h1.5a2.5 2.5 0 0 1 0 5H16 M8.5 3.5c0 1 1 1.5 1 2.5 M12 3.5c0 1 1 1.5 1 2.5" },
{ name: "綿のフェイスタオル 2枚", price: 2200, d: "M6 3.5h12v16H6z M6 7.5h12 M6 15.5h12 M9 19.5v2 M12 19.5v2 M15 19.5v2" },
{ name: "帆布のトートバッグ", price: 3300, d: "M4 9h16l-1.5 11h-13z M8.5 9V7a3.5 3.5 0 0 1 7 0v2" },
{ name: "ほうじ茶 ティーバッグ 20包", price: 1500, d: "M7 6h10v14H7z M7 10h10 M12 2.5V6 M10 14h4 M10 17h4" },
{ name: "木の箸と箸置き", price: 2200, d: "M5.5 18.5 17 3 M9 19.5 19.5 4.5 M4 21h9" },
];
const PRICE = 5500;
const STOPS = ["#a8a29e","#e7e5e4","#c8c4c0","#f5f5f4","#9c9792"];
const R = 22; // 指の半径
const CELL = 8; // 数える格子
const TH = 0.6; // 全部開く割合
const yen = (n: number) => "¥" + n.toLocaleString("ja-JP");
export default function FukubukuroScratch() {
const cv = useRef<HTMLCanvasElement>(null);
const st = useRef({ w: 0, h: 0, cols: 1, rows: 1, hit: new Uint8Array(1), count: 0, last: null as null | [number, number], row: 0, strokes: [] as number[][] });
const [pct, setPct] = useState(0);
const [open, setOpen] = useState(false);
const total = ITEMS.reduce((s, it) => s + it.price, 0);
// 膜を塗り、削った線(割合で覚えた分)を描き戻す。大きさが変わるたびに呼ぶ
const paint = () => {
const c = cv.current!;
const r = c.getBoundingClientRect();
if (!r.width || !r.height) return;
const d = window.devicePixelRatio || 1;
c.width = r.width * d;
c.height = r.height * d;
const ctx = c.getContext("2d")!;
ctx.setTransform(d, 0, 0, d, 0, 0);
ctx.globalCompositeOperation = "source-over";
const g = ctx.createLinearGradient(0, 0, r.width, r.height);
STOPS.forEach((col, i) => g.addColorStop(i / (STOPS.length - 1), col));
ctx.fillStyle = g;
ctx.fillRect(0, 0, r.width, r.height);
const cols = Math.ceil(r.width / CELL);
const rows = Math.ceil(r.height / CELL);
Object.assign(st.current, { w: r.width, h: r.height, cols, rows, hit: new Uint8Array(cols * rows), count: 0 });
for (const [a, b, e, f] of st.current.strokes) scrape(a * r.width, b * r.height, e * r.width, f * r.height);
};
useEffect(() => {
const c = cv.current!;
paint();
let pw = c.clientWidth, ph = c.clientHeight;
const ro = new ResizeObserver(() => {
if (Math.abs(c.clientWidth - pw) < 1 && Math.abs(c.clientHeight - ph) < 1) return;
pw = c.clientWidth;
ph = c.clientHeight;
paint();
});
ro.observe(c);
return () => ro.disconnect();
}, []);
const line = (x0: number, y0: number, x1: number, y1: number) => {
const s = st.current;
s.strokes.push([x0 / s.w, y0 / s.h, x1 / s.w, y1 / s.h]);
scrape(x0, y0, x1, y1);
const p = s.count / (s.cols * s.rows);
setPct(Math.floor(p * 100));
if (p >= TH) setOpen(true);
};
// 線を1本削って、格子で削れた量を数える
function scrape(x0: number, y0: number, x1: number, y1: number) {
const s = st.current;
const ctx = cv.current!.getContext("2d")!;
ctx.globalCompositeOperation = "destination-out";
ctx.lineCap = "round";
ctx.lineWidth = R * 2;
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(x1 + 0.01, y1);
ctx.stroke();
const dx = x1 - x0, dy = y1 - y0, l2 = dx * dx + dy * dy;
for (let rr = Math.max(0, Math.floor((Math.min(y0, y1) - R) / CELL)); rr <= Math.min(s.rows - 1, (Math.max(y0, y1) + R) / CELL); rr++)
for (let cc = Math.max(0, Math.floor((Math.min(x0, x1) - R) / CELL)); cc <= Math.min(s.cols - 1, (Math.max(x0, x1) + R) / CELL); cc++) {
const i = rr * s.cols + cc;
if (s.hit[i]) continue;
const px = (cc + 0.5) * CELL, py = (rr + 0.5) * CELL;
const t = l2 ? Math.max(0, Math.min(1, ((px - x0) * dx + (py - y0) * dy) / l2)) : 0;
if ((x0 + t * dx - px) ** 2 + (y0 + t * dy - py) ** 2 <= R * R) { s.hit[i] = 1; s.count++; }
}
}
const pos = (e: PointerEvent<HTMLCanvasElement>): [number, number] => {
const r = e.currentTarget.getBoundingClientRect();
return [e.clientX - r.left, e.clientY - r.top];
};
return (
<section className="w-full max-w-[560px] border border-stone-300 bg-[#fffdf8] text-stone-900">
<div className="relative m-3">
<ul className="px-4">
{ITEMS.map((it) => (
<li key={it.name} className="grid grid-cols-[36px_1fr_auto] items-center gap-3 border-b border-stone-200 py-3 text-[15px]">
<svg viewBox="0 0 24 24" aria-hidden="true" className="size-7 fill-none stroke-stone-700 [stroke-linecap:round] [stroke-linejoin:round] [stroke-width:1.5]"><path d={it.d} /></svg>
<span className="font-medium">{it.name}</span>
<span className="tabular-nums">{yen(it.price)}</span>
</li>
))}
<li className="flex justify-between py-3 text-[15px] text-stone-600">中身の定価合計<b className="tabular-nums text-stone-900">{yen(total)}</b></li>
</ul>
<canvas
ref={cv}
role="button"
tabIndex={open ? -1 : 0}
aria-label="膜を1段削る(Enter)"
aria-hidden={open}
className={`absolute inset-0 size-full cursor-crosshair touch-none transition-opacity duration-300 ease-out motion-reduce:transition-none outline-none focus-visible:ring-2 focus-visible:ring-[#d97706] ${open ? "pointer-events-none opacity-0" : ""}`}
onPointerDown={(e) => { e.currentTarget.setPointerCapture(e.pointerId); const p = pos(e); st.current.last = p; line(...p, ...p); }}
onPointerMove={(e) => { const l = st.current.last; if (!l) return; const p = pos(e); line(...l, ...p); st.current.last = p; }}
onPointerUp={() => (st.current.last = null)}
onPointerCancel={() => (st.current.last = null)}
onKeyDown={(e) => {
if (e.key !== "Enter" && e.key !== " ") return;
e.preventDefault();
const s = st.current;
const y = Math.min(s.h - R * 0.6, R * 0.8 + s.row++ * R * 1.8);
line(-R, y, s.w + R, y);
}}
/>
{!open && (
<div className={`pointer-events-none absolute inset-0 grid place-content-center justify-items-center gap-2.5 ${pct > 0 ? "opacity-0" : ""}`}>
<span className="border border-stone-300 bg-white/90 px-3.5 py-2 font-bold">こすって中身を見る</span>
</div>
)}
{!open && (
<button type="button" onClick={() => setOpen(true)} className="absolute right-3 bottom-3 min-h-11 border border-stone-900 bg-white px-4 font-bold outline-none focus-visible:ring-2 focus-visible:ring-[#d97706]">全部見る</button>
)}
</div>
<div aria-live="polite" className="border-t-2 border-[#d97706] px-7 py-4">
{open ? (
<p className="text-[15px]">中身の定価合計 <s className="text-stone-500">{yen(total)}</s> → 福袋 <span className="text-[40px] font-bold text-[#b45309] tabular-nums">{yen(PRICE)}</span></p>
) : (
<p className="text-[14px] text-stone-600">こすった量 <b className="tabular-nums text-stone-900">{pct}%</b>(60%で全部開きます)</p>
)}
</div>
</section>
);
}
Read the full description
A scratch-card style block for New Year lucky-bag (fukubukuro) product pages. A silver foil drawn on canvas covers five items (icon, name, list price) and their total; rubbing with a finger or mouse scratches it away. The scratched area is counted on an 8px grid, and past 60% the rest of the foil melts away in 300ms and a band shows "Total list price ¥12,000 → Lucky bag ¥5,500" with the saving. The contents are fixed (no lottery). A "Rub to see inside" hint and a "Show all" button sit on the foil, and Enter scratches one row at a time from the keyboard. Item names stay in the DOM, so screen readers can read them under the foil. A collapsed panel edits the five items, the bag price and the foil color (silver, gold, vermilion), and tabs copy the result as React (TSX) or dependency-free HTML+JS. It can also export a 1200×630 share image of the half-scratched card with the price masked. Reduced motion skips the melt. No dependencies.
- Added:
- 2026-11-15
- Dependencies:
- None
- tags
- #block #scratch-card #scratch-to-reveal #lucky-bag #fukubukuro #new-year-sale #ec #product-page #canvas #pointer-events #share-image #code-export #keyboard #a11y #reduced-motion #hairline #no-dependency
"use client";
import { Zen_Old_Mincho } from "next/font/google";
import {
useCallback,
useEffect,
useId,
useRef,
useState,
type KeyboardEvent,
type PointerEvent,
} from "react";
/**
* 福袋の中身をこすって見せる(スクラッチで中身5品と福袋の価格を出す)(BLK-116)
*
* 差別化: 近い既存(three-object-gallery-hero・product-configurator-3d・section-cut-viewer)は、素材や部位・断面を切り替えて何度でも眺める閲覧型。
* 本ブロックは「こすった面積を数え、60%で残りを溶かして価格の帯を出す」1回きりの開封で、操作の量そのものが結果への道のりになる。
* 英字の小見出し・見出しの「。」止め・末尾の矢印リンク・角丸・読み込み時の出現アニメは置かず、hairline 罫線と余白で組んでいる。
*
* 汎用技法メモ:
* 1. **削れた割合は画素を読まずに格子で数える**。膜を 8px の格子に分け、こすった線分から半径以内にある格子の中心に印を付けて数える。
* getImageData を毎回読まないので、pointermove ごとに数えても重くならず、割合は押した瞬間に更新できる。
* 2. **削った跡は「線の記録」として持つ**。座標を膜の幅・高さで割った値で残し、大きさが変わったら膜を描き直して跡を再生する。
* だから画面の回転や文言の変更で膜の高さが変わっても、削った所と割合がずれない。
* 3. **削るのは canvas の destination-out**。線の端と継ぎ目は round にし、太さは指の幅(直径 44px)。
* 残りを溶かすのは canvas の opacity だけを 300ms で 0 にする。prefers-reduced-motion: reduce では一度に消す。
* 4. **膜の下の品名は DOM に置く**。canvas は aria-hidden にせず「1段削る」ボタンとして Enter・Space で1段ずつ削れ、
* 品名と定価は膜がある間もスクリーンリーダーで読める。「全部見る」はキーボードと読み上げの利用者が一度で開ける出口。
*/
const mincho = Zen_Old_Mincho({
weight: ["700"],
subsets: ["latin"],
display: "swap",
preload: false,
});
const AMBER = "#d97706";
const AMBER_DEEP = "#b45309";
const INK = "#1c1917";
const MUTED = "#57534e";
const RULE = "#e7e5e4";
const PAPER = "#fffdf8";
/** 全部開く割合 */
export const THRESHOLD = 0.6;
/** 指の半径(CSS px) */
export const BRUSH = 22;
/** 数える格子の大きさ(CSS px) */
export const CELL = 8;
const MELT_MS = 300;
// --- データ -------------------------------------------------------------------------------
/** 品目のアイコン(viewBox 0 0 24 24・線画)。画面の svg と画像の Path2D で同じ d を使う */
export const ICONS = {
mug: { label: "マグ", d: "M5 8h11v7a4 4 0 0 1-4 4H9a4 4 0 0 1-4-4z M16 10h1.5a2.5 2.5 0 0 1 0 5H16 M8.5 3.5c0 1 1 1.5 1 2.5 M12 3.5c0 1 1 1.5 1 2.5" },
towel: { label: "タオル", d: "M6 3.5h12v16H6z M6 7.5h12 M6 15.5h12 M9 19.5v2 M12 19.5v2 M15 19.5v2" },
tote: { label: "バッグ", d: "M4 9h16l-1.5 11h-13z M8.5 9V7a3.5 3.5 0 0 1 7 0v2" },
tea: { label: "お茶", d: "M7 6h10v14H7z M7 10h10 M12 2.5V6 M10 14h4 M10 17h4" },
chopsticks: { label: "箸", d: "M5.5 18.5 17 3 M9 19.5 19.5 4.5 M4 21h9" },
candle: { label: "ろうそく", d: "M9 10h6v10H9z M12 10V7.5 M12 3c-1.3 1.5-1.3 2.8 0 3.8 1.3-1 1.3-2.3 0-3.8z M5.5 20h13" },
socks: { label: "靴下", d: "M8 3h6v8.5l3.6 3.6a3 3 0 0 1-4.2 4.3L8 14z M8 6.5h6" },
book: { label: "本", d: "M5 4h9a3 3 0 0 1 3 3v13H8a3 3 0 0 1-3-3z M5 17a3 3 0 0 1 3-3h9" },
} as const;
export type IconKey = keyof typeof ICONS;
export type Item = { icon: IconKey; name: string; price: number };
export type FilmKey = "silver" | "gold" | "shu";
export const FILMS: Record<FilmKey, { label: string; stops: string[]; mark: string; swatch: string }> = {
silver: { label: "銀", stops: ["#a8a29e", "#e7e5e4", "#c8c4c0", "#f5f5f4", "#9c9792"], mark: "rgba(68,64,60,.13)", swatch: "#c8c4c0" },
gold: { label: "金", stops: ["#b7862c", "#f3d98b", "#d6a945", "#fbeab0", "#a8771f"], mark: "rgba(92,62,8,.16)", swatch: "#d6a945" },
shu: { label: "朱", stops: ["#9f2f15", "#d9542f", "#c73e1d", "#e8714b", "#8f2a13"], mark: "rgba(255,240,230,.18)", swatch: "#c73e1d" },
};
export const DEFAULT_ITEMS: Item[] = [
{ icon: "mug", name: "白磁のマグカップ", price: 2800 },
{ icon: "towel", name: "綿のフェイスタオル 2枚", price: 2200 },
{ icon: "tote", name: "帆布のトートバッグ", price: 3300 },
{ icon: "tea", name: "ほうじ茶 ティーバッグ 20包", price: 1500 },
{ icon: "chopsticks", name: "木の箸と箸置き", price: 2200 },
];
export const DEFAULT_PRICE = 5500;
export const yen = (n: number) => `¥${Math.round(n).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
export const totalOf = (items: Item[]) => items.reduce((s, it) => s + it.price, 0);
/** 価格の欄に入った文字を 0〜9,999,999 の整数にする(全角数字・カンマ・円記号を許す) */
export function toPrice(raw: string) {
const half = raw.replace(/[0-9]/g, (c) => String.fromCharCode(c.charCodeAt(0) - 0xfee0)).replace(/[^0-9]/g, "");
if (!half) return 0;
return Math.min(9999999, Number(half));
}
/** 帯の下の一言 */
export function savingNote(total: number, price: number) {
if (total <= 0) return "中身の定価を入れると、差額が出ます";
const off = total - price;
if (off <= 0) return "福袋の価格が中身の定価合計以上です";
return `${off.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}円分おトク(定価合計の${Math.round((price / total) * 100)}%の価格)`;
}
// --- 削れた割合を数える格子 ------------------------------------------------------------------
export type Grid = { cols: number; rows: number; cell: number; hit: Uint8Array; count: number };
export function makeGrid(w: number, h: number, cell = CELL): Grid {
const cols = Math.max(1, Math.ceil(w / cell));
const rows = Math.max(1, Math.ceil(h / cell));
return { cols, rows, cell, hit: new Uint8Array(cols * rows), count: 0 };
}
/** 線分 (x0,y0)-(x1,y1) から半径 r 以内に中心がある格子に印を付ける。新しく付いた数を返す */
export function markSegment(g: Grid, x0: number, y0: number, x1: number, y1: number, r: number) {
const { cols, rows, cell } = g;
const minC = Math.max(0, Math.floor((Math.min(x0, x1) - r) / cell));
const maxC = Math.min(cols - 1, Math.floor((Math.max(x0, x1) + r) / cell));
const minR = Math.max(0, Math.floor((Math.min(y0, y1) - r) / cell));
const maxR = Math.min(rows - 1, Math.floor((Math.max(y0, y1) + r) / cell));
const dx = x1 - x0;
const dy = y1 - y0;
const len2 = dx * dx + dy * dy;
let added = 0;
for (let rr = minR; rr <= maxR; rr++) {
for (let cc = minC; cc <= maxC; cc++) {
const i = rr * cols + cc;
if (g.hit[i]) continue;
const px = (cc + 0.5) * cell;
const py = (rr + 0.5) * cell;
const t = len2 === 0 ? 0 : Math.max(0, Math.min(1, ((px - x0) * dx + (py - y0) * dy) / len2));
const qx = x0 + t * dx - px;
const qy = y0 + t * dy - py;
if (qx * qx + qy * qy <= r * r) {
g.hit[i] = 1;
added++;
}
}
}
g.count += added;
return added;
}
export const ratioOf = (g: Grid) => g.count / (g.cols * g.rows);
/** 線の記録(座標は膜の幅・高さで割った 0〜1) */
export type Stroke = number[];
/** キーボードで削る n 段目の線(左から右へ少し波打つ)。段の高さは指の直径の 0.9 倍 */
export function rowStroke(n: number, w: number, h: number): Stroke {
const pitch = BRUSH * 2 * 0.9;
const y = Math.min(h - BRUSH * 0.6, BRUSH * 0.8 + n * pitch);
const pts: number[] = [];
const steps = 8;
for (let k = 0; k <= steps; k++) {
const x = -BRUSH + ((w + BRUSH * 2) * k) / steps;
const yy = y + (k % 2 ? 5 : -5);
pts.push(x / w, yy / h);
}
return pts;
}
export const rowCount = (h: number) => Math.max(1, Math.ceil((h - BRUSH * 0.2) / (BRUSH * 2 * 0.9)));
/** 共有画像に描く「半分削った」跡(膜の左上から斜めに数本・0〜1 の座標) */
export const HALF_STROKES: Stroke[] = [
[0.02, 0.1, 0.3, 0.06, 0.6, 0.12, 0.92, 0.08],
[0.02, 0.24, 0.35, 0.2, 0.7, 0.27, 0.96, 0.22],
[0.04, 0.38, 0.3, 0.35, 0.58, 0.42, 0.86, 0.37],
[0.02, 0.52, 0.24, 0.48, 0.46, 0.55, 0.62, 0.5],
[0.02, 0.66, 0.16, 0.62, 0.3, 0.68],
];
// --- 膜の描画 ---------------------------------------------------------------------------------
/** 決まった並びの乱数(膜の粒) */
function rng(seed: number) {
let s = seed >>> 0;
return () => {
s = (s + 0x6d2b79f5) >>> 0;
let t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function paintFilm(ctx: CanvasRenderingContext2D, w: number, h: number, film: FilmKey, serif: string) {
const f = FILMS[film];
ctx.save();
ctx.globalCompositeOperation = "source-over";
const g = ctx.createLinearGradient(0, 0, w, h);
f.stops.forEach((c, i) => g.addColorStop(i / (f.stops.length - 1), c));
ctx.fillStyle = g;
ctx.fillRect(0, 0, w, h);
// 斜めの光の筋
ctx.globalAlpha = 0.18;
ctx.fillStyle = "#ffffff";
for (let x = -h; x < w; x += 46) {
ctx.beginPath();
ctx.moveTo(x, h);
ctx.lineTo(x + h, 0);
ctx.lineTo(x + h + 10, 0);
ctx.lineTo(x + 10, h);
ctx.fill();
}
// 粒
const rand = rng(11);
for (let i = 0; i < (w * h) / 90; i++) {
ctx.globalAlpha = 0.05 + rand() * 0.08;
ctx.fillStyle = rand() > 0.5 ? "#ffffff" : "#000000";
ctx.fillRect(rand() * w, rand() * h, 1.2, 1.2);
}
// 地紋の「福」
ctx.globalAlpha = 1;
ctx.fillStyle = f.mark;
ctx.font = `700 22px ${serif}`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
for (let y = 22, row = 0; y < h + 22; y += 48, row++) {
for (let x = row % 2 ? 46 : 18; x < w + 22; x += 56) ctx.fillText("福", x, y);
}
ctx.restore();
}
function scratchStroke(ctx: CanvasRenderingContext2D, pts: Stroke, w: number, h: number, r = BRUSH) {
ctx.save();
ctx.globalCompositeOperation = "destination-out";
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.lineWidth = r * 2;
ctx.strokeStyle = "#000";
ctx.fillStyle = "#000";
if (pts.length === 2) {
ctx.beginPath();
ctx.arc(pts[0] * w, pts[1] * h, r, 0, Math.PI * 2);
ctx.fill();
} else {
ctx.beginPath();
ctx.moveTo(pts[0] * w, pts[1] * h);
for (let i = 2; i < pts.length; i += 2) ctx.lineTo(pts[i] * w, pts[i + 1] * h);
ctx.stroke();
}
ctx.restore();
}
function markStroke(g: Grid, pts: Stroke, w: number, h: number, r = BRUSH) {
if (pts.length === 2) return markSegment(g, pts[0] * w, pts[1] * h, pts[0] * w, pts[1] * h, r);
let n = 0;
for (let i = 2; i < pts.length; i += 2) n += markSegment(g, pts[i - 2] * w, pts[i - 1] * h, pts[i] * w, pts[i + 1] * h, r);
return n;
}
// --- 共有画像(1200×630・半分削った状態) ------------------------------------------------------
async function renderShare(items: Item[], price: number, film: FilmKey, sans: string, serif: string) {
const W = 1200;
const H = 630;
const cv = document.createElement("canvas");
cv.width = W;
cv.height = H;
const ctx = cv.getContext("2d");
if (!ctx) return null;
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, W, H);
ctx.strokeStyle = RULE;
ctx.lineWidth = 2;
ctx.strokeRect(1, 1, W - 2, H - 2);
// 左: 福袋のカード
const cx = 56;
const cy = 56;
const cw = 560;
const ch = 518;
ctx.fillStyle = PAPER;
ctx.fillRect(cx, cy, cw, ch);
ctx.strokeStyle = "#d6d3d1";
ctx.lineWidth = 1.5;
ctx.strokeRect(cx + 0.5, cy + 0.5, cw - 1, ch - 1);
// 見出し
ctx.strokeStyle = AMBER;
ctx.lineWidth = 2.5;
ctx.strokeRect(cx + 28, cy + 24, 52, 52);
ctx.fillStyle = AMBER_DEEP;
ctx.font = `700 34px ${serif}`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("福", cx + 54, cy + 51);
ctx.textAlign = "left";
ctx.fillStyle = INK;
ctx.font = `700 26px ${sans}`;
ctx.fillText("初売りの福袋", cx + 100, cy + 40);
ctx.fillStyle = MUTED;
ctx.font = `500 17px ${sans}`;
ctx.fillText(`中身${items.length}品・中身は全員同じです`, cx + 100, cy + 66);
// 品目
const top = cy + 100;
const rowH = 70;
const fh = rowH * items.length + 64;
items.forEach((it, i) => {
const y = top + i * rowH;
ctx.strokeStyle = RULE;
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(cx + 28, y + rowH);
ctx.lineTo(cx + cw - 28, y + rowH);
ctx.stroke();
ctx.save();
ctx.translate(cx + 30, y + 14);
ctx.scale(42 / 24, 42 / 24);
ctx.strokeStyle = "#44403c";
ctx.lineWidth = 1.5;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.stroke(new Path2D(ICONS[it.icon].d));
ctx.restore();
ctx.fillStyle = INK;
ctx.font = `500 22px ${sans}`;
ctx.textAlign = "left";
ctx.fillText(clip(ctx, it.name, 330), cx + 92, y + rowH / 2);
ctx.textAlign = "right";
ctx.fillText(yen(it.price), cx + cw - 28, y + rowH / 2);
});
ctx.textAlign = "left";
ctx.fillStyle = MUTED;
ctx.font = `500 19px ${sans}`;
ctx.fillText("中身の定価合計", cx + 28, top + rowH * items.length + 32);
ctx.textAlign = "right";
ctx.fillStyle = INK;
ctx.font = `700 24px ${sans}`;
ctx.fillText(yen(totalOf(items)), cx + cw - 28, top + rowH * items.length + 32);
// 膜(半分削った跡を抜く)
const fw = cw - 24;
const film2 = document.createElement("canvas");
film2.width = fw;
film2.height = fh;
const fctx = film2.getContext("2d");
if (fctx) {
paintFilm(fctx, fw, fh, film, serif);
for (const s of HALF_STROKES) scratchStroke(fctx, s, fw, fh, 30);
ctx.drawImage(film2, cx + 12, top - 8);
}
// 右: 題と価格の伏せ字
const rx = 668;
ctx.textAlign = "left";
ctx.textBaseline = "alphabetic";
ctx.fillStyle = AMBER_DEEP;
ctx.font = `700 22px ${sans}`;
ctx.fillText("こすって中身を見る", rx, 140);
ctx.fillStyle = INK;
ctx.font = `700 54px ${serif}`;
ctx.fillText("福袋の中身、", rx, 220);
ctx.fillText("半分まで見えた", rx, 290);
ctx.fillStyle = AMBER;
ctx.fillRect(rx, 330, 64, 3);
ctx.fillStyle = MUTED;
ctx.font = `500 24px ${sans}`;
ctx.fillText(`中身${items.length}品の定価合計 ${yen(totalOf(items))}`, rx, 384);
ctx.fillStyle = INK;
ctx.font = `700 30px ${sans}`;
const masked = yen(price).replace(/[0-9]/g, "?");
ctx.fillText(`福袋の価格 ${masked}`, rx, 434);
ctx.fillStyle = MUTED;
ctx.font = `500 17px ${sans}`;
ctx.fillText("残りをこすると価格が出ます", rx, 470);
ctx.fillStyle = "#78716c";
ctx.font = `500 16px ${sans}`;
ctx.fillText("designs.first-ch.com/d/fukubukuro-scratch-reveal", rx, 568);
return await new Promise<string | null>((res) =>
cv.toBlob((b) => res(b ? URL.createObjectURL(b) : null), "image/png"),
);
}
function clip(ctx: CanvasRenderingContext2D, s: string, max: number) {
if (ctx.measureText(s).width <= max) return s;
let t = s;
while (t.length > 1 && ctx.measureText(`${t}…`).width > max) t = t.slice(0, -1);
return `${t}…`;
}
// --- 書き出すコード -------------------------------------------------------------------------
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] ?? c);
/** 依存なしの HTML+JS(品目・価格・膜の色を入れた1ファイル) */
export function htmlCode(items: Item[], price: number, film: FilmKey) {
const total = totalOf(items);
const rows = items
.map(
(it) =>
` <li><svg viewBox="0 0 24 24" aria-hidden="true"><path d="${ICONS[it.icon].d}"/></svg><span>${esc(it.name)}</span><span class="p">${yen(it.price)}</span></li>`,
)
.join("\n");
return `<!-- 福袋の中身をこすって見せる(依存なし) -->
<section class="fk">
<div class="fk-card">
<div class="fk-body">
<ul>
${rows}
<li class="fk-total"><span>中身の定価合計</span><span class="p">${yen(total)}</span></li>
</ul>
<canvas class="fk-film" role="button" tabindex="0" aria-label="膜を1段削る(Enter)"></canvas>
<div class="fk-guide"><span>こすって中身を見る</span></div>
<button type="button" class="fk-all">全部見る</button>
</div>
<div class="fk-band" aria-live="polite">
<p class="fk-meter">こすった量 <b>0%</b>(60%で全部開きます)</p>
</div>
</div>
</section>
<style>
.fk-card{max-width:560px;border:1px solid #d6d3d1;background:#fffdf8;font-family:"Noto Sans JP",sans-serif;color:#1c1917}
.fk-body{position:relative;margin:12px}
.fk ul{list-style:none;margin:0;padding:0 16px}
.fk li{display:grid;grid-template-columns:36px 1fr auto;gap:12px;align-items:center;padding:12px 0;border-bottom:1px solid #e7e5e4;font-size:15px}
.fk li svg{width:28px;height:28px;fill:none;stroke:#44403c;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}
.fk .p{font-variant-numeric:tabular-nums}
.fk-total{grid-template-columns:1fr auto!important;border-bottom:0!important;color:#57534e}
.fk-film{position:absolute;inset:0;width:100%;height:100%;touch-action:none;cursor:crosshair;transition:opacity .3s ease-out}
.fk-film:focus-visible,.fk-all:focus-visible{outline:2px solid #d97706;outline-offset:2px}
.fk-guide{position:absolute;inset:0;display:grid;place-content:center;justify-items:center;gap:10px;pointer-events:none;transition:opacity .2s}
.fk-guide span{background:rgba(255,255,255,.92);border:1px solid #d6d3d1;padding:8px 14px;font-weight:700}
.fk-all{position:absolute;right:12px;bottom:12px;min-height:44px;padding:0 16px;border:1px solid #1c1917;background:#fff;font:inherit;font-weight:700;cursor:pointer}
.fk-band{border-top:2px solid #d97706;padding:16px 28px;min-height:64px}
.fk-band .now{font-size:40px;font-weight:700;color:#b45309}
.fk.open .fk-film{opacity:0;pointer-events:none}
.fk.open .fk-guide{opacity:0}
.fk.open .fk-all{display:none}
@media (prefers-reduced-motion:reduce){.fk-film,.fk-guide{transition:none}}
</style>
<script>
(() => {
const root = document.currentScript.previousElementSibling.previousElementSibling;
const cv = root.querySelector(".fk-film"), ctx = cv.getContext("2d");
const band = root.querySelector(".fk-band"), guide = root.querySelector(".fk-guide");
const STOPS = ${JSON.stringify(FILMS[film].stops)}, R = ${BRUSH}, CELL = ${CELL}, TH = ${THRESHOLD};
let w = 0, h = 0, hit, count = 0, cols = 0, rows = 0, last = null, open = false, row = 0;
const strokes = []; // 削った線(幅・高さに対する割合)。大きさが変わったら描き戻す
function paint() {
const r = cv.getBoundingClientRect(), d = devicePixelRatio || 1;
if (!r.width || !r.height) return;
w = r.width; h = r.height; cv.width = w * d; cv.height = h * d; ctx.setTransform(d, 0, 0, d, 0, 0);
ctx.globalCompositeOperation = "source-over";
const g = ctx.createLinearGradient(0, 0, w, h);
STOPS.forEach((c, i) => g.addColorStop(i / (STOPS.length - 1), c));
ctx.fillStyle = g; ctx.fillRect(0, 0, w, h);
cols = Math.ceil(w / CELL); rows = Math.ceil(h / CELL); hit = new Uint8Array(cols * rows); count = 0;
for (const [a, b, c, e] of strokes) scrape(a * w, b * h, c * w, e * h);
}
function mark(x0, y0, x1, y1) {
const dx = x1 - x0, dy = y1 - y0, l2 = dx * dx + dy * dy;
for (let r = Math.max(0, ((Math.min(y0, y1) - R) / CELL) | 0); r <= Math.min(rows - 1, (Math.max(y0, y1) + R) / CELL); r++)
for (let c = Math.max(0, ((Math.min(x0, x1) - R) / CELL) | 0); c <= Math.min(cols - 1, (Math.max(x0, x1) + R) / CELL); c++) {
const i = r * cols + c; if (hit[i]) continue;
const px = (c + .5) * CELL, py = (r + .5) * CELL;
const t = l2 ? Math.max(0, Math.min(1, ((px - x0) * dx + (py - y0) * dy) / l2)) : 0;
const qx = x0 + t * dx - px, qy = y0 + t * dy - py;
if (qx * qx + qy * qy <= R * R) { hit[i] = 1; count++; }
}
}
function scrape(x0, y0, x1, y1) {
ctx.globalCompositeOperation = "destination-out"; ctx.lineCap = "round"; ctx.lineWidth = R * 2;
ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x1 + .01, y1); ctx.stroke();
mark(x0, y0, x1, y1);
}
function line(x0, y0, x1, y1) {
strokes.push([x0 / w, y0 / h, x1 / w, y1 / h]);
scrape(x0, y0, x1, y1); guide.style.opacity = "0"; update();
}
function update() {
const p = count / (cols * rows);
if (!open) band.querySelector("b").textContent = Math.floor(p * 100) + "%";
if (p >= TH) reveal();
}
function reveal() {
if (open) return; open = true; root.classList.add("open");
cv.tabIndex = -1; cv.setAttribute("aria-hidden", "true");
band.innerHTML = '<p>中身の定価合計 <s>${yen(total)}</s> → 福袋 <span class="now">${yen(price)}</span></p><p>${savingNote(total, price)}</p>';
}
const pos = (e) => { const r = cv.getBoundingClientRect(); return [e.clientX - r.left, e.clientY - r.top]; };
cv.addEventListener("pointerdown", (e) => { cv.setPointerCapture(e.pointerId); last = pos(e); line(...last, ...last); });
cv.addEventListener("pointermove", (e) => { if (!last) return; const p = pos(e); line(...last, ...p); last = p; });
["pointerup", "pointercancel"].forEach((t) => cv.addEventListener(t, () => (last = null)));
cv.addEventListener("keydown", (e) => {
if (e.key !== "Enter" && e.key !== " ") return; e.preventDefault();
const y = Math.min(h - R * .6, R * .8 + row++ * R * 1.8); line(-R, y, w + R, y);
});
root.querySelector(".fk-all").addEventListener("click", reveal);
paint();
// 画面の回転や幅の変化で膜の大きさが変わったら、画素数と格子を合わせ直す
let pw = cv.clientWidth, ph = cv.clientHeight;
const ro = new ResizeObserver(() => {
if (open) return ro.disconnect();
if (Math.abs(cv.clientWidth - pw) < 1 && Math.abs(cv.clientHeight - ph) < 1) return;
pw = cv.clientWidth; ph = cv.clientHeight; paint();
});
ro.observe(cv);
})();
</script>`;
}
/** React + Tailwind の部品(品目・価格・膜の色を定数に入れた1ファイル) */
export function reactCode(items: Item[], price: number, film: FilmKey) {
const data = items.map((it) => ` { name: ${JSON.stringify(it.name)}, price: ${it.price}, d: ${JSON.stringify(ICONS[it.icon].d)} },`).join("\n");
return `"use client";
import { useEffect, useRef, useState, type PointerEvent } from "react";
// 福袋の中身をこすって見せる(依存なし・React + Tailwind CSS v4)
const ITEMS = [
${data}
];
const PRICE = ${price};
const STOPS = ${JSON.stringify(FILMS[film].stops)};
const R = ${BRUSH}; // 指の半径
const CELL = ${CELL}; // 数える格子
const TH = ${THRESHOLD}; // 全部開く割合
const yen = (n: number) => "¥" + n.toLocaleString("ja-JP");
export default function FukubukuroScratch() {
const cv = useRef<HTMLCanvasElement>(null);
const st = useRef({ w: 0, h: 0, cols: 1, rows: 1, hit: new Uint8Array(1), count: 0, last: null as null | [number, number], row: 0, strokes: [] as number[][] });
const [pct, setPct] = useState(0);
const [open, setOpen] = useState(false);
const total = ITEMS.reduce((s, it) => s + it.price, 0);
// 膜を塗り、削った線(割合で覚えた分)を描き戻す。大きさが変わるたびに呼ぶ
const paint = () => {
const c = cv.current!;
const r = c.getBoundingClientRect();
if (!r.width || !r.height) return;
const d = window.devicePixelRatio || 1;
c.width = r.width * d;
c.height = r.height * d;
const ctx = c.getContext("2d")!;
ctx.setTransform(d, 0, 0, d, 0, 0);
ctx.globalCompositeOperation = "source-over";
const g = ctx.createLinearGradient(0, 0, r.width, r.height);
STOPS.forEach((col, i) => g.addColorStop(i / (STOPS.length - 1), col));
ctx.fillStyle = g;
ctx.fillRect(0, 0, r.width, r.height);
const cols = Math.ceil(r.width / CELL);
const rows = Math.ceil(r.height / CELL);
Object.assign(st.current, { w: r.width, h: r.height, cols, rows, hit: new Uint8Array(cols * rows), count: 0 });
for (const [a, b, e, f] of st.current.strokes) scrape(a * r.width, b * r.height, e * r.width, f * r.height);
};
useEffect(() => {
const c = cv.current!;
paint();
let pw = c.clientWidth, ph = c.clientHeight;
const ro = new ResizeObserver(() => {
if (Math.abs(c.clientWidth - pw) < 1 && Math.abs(c.clientHeight - ph) < 1) return;
pw = c.clientWidth;
ph = c.clientHeight;
paint();
});
ro.observe(c);
return () => ro.disconnect();
}, []);
const line = (x0: number, y0: number, x1: number, y1: number) => {
const s = st.current;
s.strokes.push([x0 / s.w, y0 / s.h, x1 / s.w, y1 / s.h]);
scrape(x0, y0, x1, y1);
const p = s.count / (s.cols * s.rows);
setPct(Math.floor(p * 100));
if (p >= TH) setOpen(true);
};
// 線を1本削って、格子で削れた量を数える
function scrape(x0: number, y0: number, x1: number, y1: number) {
const s = st.current;
const ctx = cv.current!.getContext("2d")!;
ctx.globalCompositeOperation = "destination-out";
ctx.lineCap = "round";
ctx.lineWidth = R * 2;
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(x1 + 0.01, y1);
ctx.stroke();
const dx = x1 - x0, dy = y1 - y0, l2 = dx * dx + dy * dy;
for (let rr = Math.max(0, Math.floor((Math.min(y0, y1) - R) / CELL)); rr <= Math.min(s.rows - 1, (Math.max(y0, y1) + R) / CELL); rr++)
for (let cc = Math.max(0, Math.floor((Math.min(x0, x1) - R) / CELL)); cc <= Math.min(s.cols - 1, (Math.max(x0, x1) + R) / CELL); cc++) {
const i = rr * s.cols + cc;
if (s.hit[i]) continue;
const px = (cc + 0.5) * CELL, py = (rr + 0.5) * CELL;
const t = l2 ? Math.max(0, Math.min(1, ((px - x0) * dx + (py - y0) * dy) / l2)) : 0;
if ((x0 + t * dx - px) ** 2 + (y0 + t * dy - py) ** 2 <= R * R) { s.hit[i] = 1; s.count++; }
}
}
const pos = (e: PointerEvent<HTMLCanvasElement>): [number, number] => {
const r = e.currentTarget.getBoundingClientRect();
return [e.clientX - r.left, e.clientY - r.top];
};
return (
<section className="w-full max-w-[560px] border border-stone-300 bg-[#fffdf8] text-stone-900">
<div className="relative m-3">
<ul className="px-4">
{ITEMS.map((it) => (
<li key={it.name} className="grid grid-cols-[36px_1fr_auto] items-center gap-3 border-b border-stone-200 py-3 text-[15px]">
<svg viewBox="0 0 24 24" aria-hidden="true" className="size-7 fill-none stroke-stone-700 [stroke-linecap:round] [stroke-linejoin:round] [stroke-width:1.5]"><path d={it.d} /></svg>
<span className="font-medium">{it.name}</span>
<span className="tabular-nums">{yen(it.price)}</span>
</li>
))}
<li className="flex justify-between py-3 text-[15px] text-stone-600">中身の定価合計<b className="tabular-nums text-stone-900">{yen(total)}</b></li>
</ul>
<canvas
ref={cv}
role="button"
tabIndex={open ? -1 : 0}
aria-label="膜を1段削る(Enter)"
aria-hidden={open}
className={\`absolute inset-0 size-full cursor-crosshair touch-none transition-opacity duration-300 ease-out motion-reduce:transition-none outline-none focus-visible:ring-2 focus-visible:ring-[#d97706] \${open ? "pointer-events-none opacity-0" : ""}\`}
onPointerDown={(e) => { e.currentTarget.setPointerCapture(e.pointerId); const p = pos(e); st.current.last = p; line(...p, ...p); }}
onPointerMove={(e) => { const l = st.current.last; if (!l) return; const p = pos(e); line(...l, ...p); st.current.last = p; }}
onPointerUp={() => (st.current.last = null)}
onPointerCancel={() => (st.current.last = null)}
onKeyDown={(e) => {
if (e.key !== "Enter" && e.key !== " ") return;
e.preventDefault();
const s = st.current;
const y = Math.min(s.h - R * 0.6, R * 0.8 + s.row++ * R * 1.8);
line(-R, y, s.w + R, y);
}}
/>
{!open && (
<div className={\`pointer-events-none absolute inset-0 grid place-content-center justify-items-center gap-2.5 \${pct > 0 ? "opacity-0" : ""}\`}>
<span className="border border-stone-300 bg-white/90 px-3.5 py-2 font-bold">こすって中身を見る</span>
</div>
)}
{!open && (
<button type="button" onClick={() => setOpen(true)} className="absolute right-3 bottom-3 min-h-11 border border-stone-900 bg-white px-4 font-bold outline-none focus-visible:ring-2 focus-visible:ring-[#d97706]">全部見る</button>
)}
</div>
<div aria-live="polite" className="border-t-2 border-[#d97706] px-7 py-4">
{open ? (
<p className="text-[15px]">中身の定価合計 <s className="text-stone-500">{yen(total)}</s> → 福袋 <span className="text-[40px] font-bold text-[#b45309] tabular-nums">{yen(PRICE)}</span></p>
) : (
<p className="text-[14px] text-stone-600">こすった量 <b className="tabular-nums text-stone-900">{pct}%</b>(60%で全部開きます)</p>
)}
</div>
</section>
);
}
`;
}
// --- 本体 -------------------------------------------------------------------------------------
const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-[#d97706] focus-visible:ring-offset-2";
const btn = `inline-flex min-h-11 items-center justify-center gap-2 border px-4 text-[14px] font-bold transition-colors duration-150 motion-reduce:transition-none ${focusRing}`;
function Icon({ d, className }: { d: string; className?: string }) {
return (
<svg viewBox="0 0 24 24" aria-hidden="true" className={className} fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
<path d={d} />
</svg>
);
}
function Swap({ on, idle, done }: { on: boolean; idle: string; done: string }) {
return (
<span className="grid">
<span className={`[grid-area:1/1] transition-opacity duration-150 motion-reduce:transition-none ${on ? "opacity-0" : "opacity-100"}`}>{idle}</span>
<span aria-hidden={!on} className={`[grid-area:1/1] transition-opacity duration-150 motion-reduce:transition-none ${on ? "opacity-100" : "opacity-0"}`}>
{done}
</span>
</span>
);
}
/** ほかの季節の部品 */
const RELATED = [
{ href: "/d/omikuji-shake-card", title: "縦書きおみくじ", note: "筒を振って引き、紙を画像で保存" },
{ href: "/d/sekki-seasonal-header", title: "二十四節気の見出し帯", note: "日付で季節の言葉と色が替わる" },
];
export type FukubukuroScratchProps = {
headingTag?: "h1" | "h2" | "p";
items?: Item[];
price?: number;
film?: FilmKey;
};
export default function FukubukuroScratchReveal({
headingTag,
items: initialItems = DEFAULT_ITEMS,
price: initialPrice = DEFAULT_PRICE,
film: initialFilm = "silver",
}: FukubukuroScratchProps) {
const Heading = headingTag ?? "h2";
const uid = useId();
const [items, setItems] = useState<Item[]>(initialItems);
const [price, setPrice] = useState(initialPrice);
const [film, setFilm] = useState<FilmKey>(initialFilm);
const [pct, setPct] = useState(0);
const [open, setOpen] = useState(false);
const [started, setStarted] = useState(false);
const [tab, setTab] = useState<"react" | "html">("react");
const [copied, setCopied] = useState(false);
const [share, setShare] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const rootRef = useRef<HTMLElement>(null);
const markRef = useRef<HTMLSpanElement>(null);
const bodyRef = useRef<HTMLDivElement>(null);
const cvRef = useRef<HTMLCanvasElement>(null);
// 描画の状態は ref に持つ(pointermove ごとに再描画しない)
const s = useRef({ w: 0, h: 0, grid: makeGrid(1, 1), strokes: [] as Stroke[], cur: null as Stroke | null, last: null as [number, number] | null, row: 0, open: false });
const total = totalOf(items);
const reveal = useCallback(() => {
if (s.current.open) return;
s.current.open = true;
setOpen(true);
setPct(100);
try {
navigator.vibrate?.(18);
} catch {
/* 振動できない端末では何もしない */
}
}, []);
const report = useCallback(() => {
const r = ratioOf(s.current.grid);
setPct(Math.min(100, Math.floor(r * 100)));
if (r >= THRESHOLD) reveal();
}, [reveal]);
/** 膜を描き直し、記録した跡を再生する(大きさ・色が変わったとき) */
const repaint = useCallback(() => {
const cv = cvRef.current;
const body = bodyRef.current;
if (!cv || !body) return;
const w = body.clientWidth;
const h = body.clientHeight;
if (w === 0 || h === 0) return;
const d = Math.min(2, window.devicePixelRatio || 1);
cv.width = Math.round(w * d);
cv.height = Math.round(h * d);
const ctx = cv.getContext("2d");
if (!ctx) return;
ctx.setTransform(d, 0, 0, d, 0, 0);
const serif = markRef.current ? getComputedStyle(markRef.current).fontFamily : "serif";
paintFilm(ctx, w, h, film, serif);
const st = s.current;
st.w = w;
st.h = h;
st.grid = makeGrid(w, h);
for (const k of st.strokes) {
scratchStroke(ctx, k, w, h);
markStroke(st.grid, k, w, h);
}
if (st.strokes.length) report();
}, [film, report]);
useEffect(() => {
const body = bodyRef.current;
if (!body) return;
repaint();
let pw = body.clientWidth;
let ph = body.clientHeight;
const ro = new ResizeObserver(() => {
if (Math.abs(body.clientWidth - pw) < 1 && Math.abs(body.clientHeight - ph) < 1) return;
pw = body.clientWidth;
ph = body.clientHeight;
repaint();
});
ro.observe(body);
// 書体が届いたら地紋の「福」を描き直す
document.fonts?.ready.then(() => repaint());
return () => ro.disconnect();
}, [repaint]);
/** 今の線に点を足して、膜を削り格子を数える */
const drawTo = (x: number, y: number) => {
const st = s.current;
const cv = cvRef.current;
const ctx = cv?.getContext("2d");
if (!ctx || !st.cur || !st.last) return;
const [lx, ly] = st.last;
st.cur.push(x / st.w, y / st.h);
scratchStroke(ctx, [lx / st.w, ly / st.h, x / st.w, y / st.h], st.w, st.h);
markSegment(st.grid, lx, ly, x, y, BRUSH);
st.last = [x, y];
report();
};
const onDown = (e: PointerEvent<HTMLCanvasElement>) => {
if (s.current.open) return;
e.currentTarget.setPointerCapture(e.pointerId);
const r = e.currentTarget.getBoundingClientRect();
const x = e.clientX - r.left;
const y = e.clientY - r.top;
const st = s.current;
st.cur = [x / st.w, y / st.h];
st.strokes.push(st.cur);
st.last = [x, y];
const ctx = cvRef.current?.getContext("2d");
if (ctx) scratchStroke(ctx, st.cur, st.w, st.h);
markSegment(st.grid, x, y, x, y, BRUSH);
setStarted(true);
report();
};
const onMove = (e: PointerEvent<HTMLCanvasElement>) => {
if (!s.current.cur) return;
const r = e.currentTarget.getBoundingClientRect();
drawTo(e.clientX - r.left, e.clientY - r.top);
};
const onUp = () => {
s.current.cur = null;
s.current.last = null;
};
const onKey = (e: KeyboardEvent<HTMLCanvasElement>) => {
if (e.key !== "Enter" && e.key !== " ") return;
e.preventDefault();
const st = s.current;
if (st.open) return;
const k = rowStroke(st.row % rowCount(st.h), st.w, st.h);
st.row++;
st.strokes.push(k);
const ctx = cvRef.current?.getContext("2d");
if (ctx) scratchStroke(ctx, k, st.w, st.h);
markStroke(st.grid, k, st.w, st.h);
setStarted(true);
report();
};
const reset = () => {
const st = s.current;
st.strokes = [];
st.row = 0;
st.open = false;
setOpen(false);
setStarted(false);
setPct(0);
repaint();
window.requestAnimationFrame(() => cvRef.current?.focus());
};
const setItem = (i: number, patch: Partial<Item>) => setItems((xs) => xs.map((x, k) => (k === i ? { ...x, ...patch } : x)));
const code = tab === "react" ? reactCode(items, price, film) : htmlCode(items, price, film);
const copy = async () => {
try {
await navigator.clipboard.writeText(code);
} catch {
return;
}
setCopied(true);
window.setTimeout(() => setCopied(false), 1500);
};
const makeShare = async () => {
setBusy(true);
const sans = rootRef.current ? getComputedStyle(rootRef.current).fontFamily : "sans-serif";
const serif = markRef.current ? getComputedStyle(markRef.current).fontFamily : "serif";
await document.fonts?.ready;
const url = await renderShare(items, price, film, sans, serif);
setBusy(false);
if (!url) return;
setShare((old) => {
if (old) URL.revokeObjectURL(old);
return url;
});
};
const off = total - price;
return (
<section
ref={rootRef}
aria-labelledby={`${uid}-h`}
data-open={open ? "true" : "false"}
className="@container w-full max-w-5xl border border-stone-200 bg-white font-sans text-stone-900"
>
<div className="grid grid-cols-[minmax(0,1fr)] gap-y-8 px-5 py-7 @[48rem]:grid-cols-[minmax(0,1.1fr)_minmax(0,1fr)] @[48rem]:gap-x-12 @[48rem]:px-10 @[48rem]:py-10">
{/* 題と一言(広い幅では右の列の上) */}
<div className="@[48rem]:col-start-2 @[48rem]:row-start-1">
<Heading id={`${uid}-h`} className="text-[clamp(1.45rem,4.6cqi,2rem)] leading-[1.35] font-bold tracking-[0.02em] [word-break:keep-all]">
福袋の中身を、<wbr />
こすって見せる
</Heading>
<p className="mt-3 max-w-[30em] text-[15px] leading-[1.85] text-stone-700">
銀色の膜を指やマウスでこすると、中身{items.length}品と福袋の価格が出ます。中身は毎回同じで、抽選はしません。
</p>
</div>
{/* 福袋のカード(膜と結果) */}
<div className="@[48rem]:col-start-1 @[48rem]:row-span-3 @[48rem]:row-start-1">
<div className="border border-stone-300" style={{ background: PAPER }}>
<div className="flex items-center gap-4 px-6 pt-5 pb-1">
<span
ref={markRef}
aria-hidden="true"
className={`${mincho.className} grid size-12 shrink-0 place-items-center border-2 border-[#d97706] text-[28px] leading-none text-[#b45309]`}
>
福
</span>
<div>
<p className="text-[18px] leading-[1.4] font-bold">初売りの福袋</p>
<p className="text-[13px] leading-[1.6] text-stone-600">中身{items.length}品・中身は全員同じです</p>
</div>
</div>
<div ref={bodyRef} className="relative mx-3 mt-3">
<ul className="px-3" aria-label="福袋の中身">
{items.map((it, i) => (
<li key={i} className="grid grid-cols-[2.5rem_minmax(0,1fr)_auto] items-center gap-3 border-b border-stone-200 py-3">
<span className="grid size-10 place-items-center border border-stone-200 bg-white text-stone-700">
<Icon d={ICONS[it.icon].d} className="size-6" />
</span>
<span className="text-[15px] leading-[1.5] font-medium [overflow-wrap:anywhere]">{it.name || "(品名)"}</span>
<span className="font-display text-[15px] font-semibold tabular-nums">{yen(it.price)}</span>
</li>
))}
<li className="flex items-baseline justify-between gap-3 py-3.5">
<span className="text-[14px] text-stone-600">中身の定価合計</span>
<span className="font-display text-[18px] font-bold tabular-nums">{yen(total)}</span>
</li>
</ul>
<canvas
ref={cvRef}
role="button"
tabIndex={open ? -1 : 0}
aria-label="膜を1段削る(Enter)"
aria-hidden={open}
onPointerDown={onDown}
onPointerMove={onMove}
onPointerUp={onUp}
onPointerCancel={onUp}
onKeyDown={onKey}
className={`scratch-film absolute inset-0 size-full cursor-crosshair touch-none transition-opacity ease-out motion-reduce:transition-none ${focusRing} ${open ? "pointer-events-none opacity-0" : "opacity-100"}`}
style={{ transitionDuration: `${MELT_MS}ms` }}
/>
{/* 案内と「全部見る」(こすり始めたら案内は消し、ボタンは隅へ残す) */}
{!open && (
<div className="pointer-events-none absolute inset-0">
<div
className={`absolute inset-0 grid place-content-center justify-items-center gap-3 transition-opacity duration-200 motion-reduce:transition-none ${started ? "opacity-0" : "opacity-100"}`}
>
<span className="flex items-center gap-2 border border-stone-300 bg-white/95 px-4 py-2.5 text-[15px] font-bold text-stone-900">
<svg viewBox="0 0 24 24" aria-hidden="true" className="size-5 text-[#b45309]" fill="none" stroke="currentColor" strokeWidth={1.8} strokeLinecap="round">
<path d="M3 15c3-4 5 2 8-2s5 2 8-2 M3 20c3-4 5 2 8-2s5 2 8-2" />
</svg>
こすって中身を見る
</span>
</div>
<button
type="button"
onClick={reveal}
className={`reveal-all pointer-events-auto absolute right-3 bottom-3 border-stone-900 bg-white text-stone-900 hover:bg-stone-100 ${btn}`}
>
全部見る
</button>
</div>
)}
</div>
{/* 帯: こすった量 → 価格 */}
<div className="relative mt-1 min-h-[7.5rem] border-t-2 border-[#d97706] px-6 py-4">
<div
aria-hidden={open}
className={`transition-opacity duration-200 motion-reduce:transition-none ${open ? "invisible absolute inset-x-6 top-4 opacity-0" : "opacity-100"}`}
>
<p className="flex items-baseline justify-between text-[14px] text-stone-700">
<span>こすった量</span>
<span className="font-display text-[22px] font-bold text-stone-900 tabular-nums">{pct}%</span>
</p>
<div className="relative mt-2 h-2 overflow-hidden bg-stone-200" aria-hidden="true">
<div
className="h-full origin-left bg-[#d97706] transition-transform duration-100 motion-reduce:transition-none"
style={{ transform: `scaleX(${Math.min(1, pct / (THRESHOLD * 100))})` }}
/>
</div>
<p className="mt-2 text-[13px] text-stone-600">60%までこすると、残りが溶けて福袋の価格が出ます</p>
</div>
<div
className={`transition-[opacity,transform] ease-out motion-reduce:transform-none motion-reduce:transition-none ${open ? "translate-y-0 opacity-100" : "pointer-events-none invisible absolute inset-x-6 top-4 translate-y-2 opacity-0"}`}
style={{ transitionDuration: `${MELT_MS}ms` }}
>
<p className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
<span className="text-[14px] text-stone-600">中身の定価合計</span>
<s className="font-display text-[18px] font-semibold text-stone-500 tabular-nums decoration-stone-400">{yen(total)}</s>
<span className="inline-flex flex-wrap items-baseline gap-x-3 whitespace-nowrap">
<span aria-hidden="true" className="text-[18px] text-stone-400">
→
</span>
<span className="sr-only">から</span>
<span className="text-[14px] font-bold text-stone-900">福袋</span>
<span className="price-now font-display text-[clamp(2.2rem,8cqi,3rem)] leading-none font-bold text-[#b45309] tabular-nums">{yen(price)}</span>
</span>
</p>
<p className={`mt-2 text-[14px] font-bold ${off > 0 && total > 0 ? "text-stone-900" : "text-stone-600"}`}>
{off > 0 && total > 0 && <span className="mr-2 inline-block bg-[#d97706] px-1.5 text-white">お得</span>}
{savingNote(total, price)}
</p>
</div>
</div>
</div>
{/* 操作 */}
<div className="mt-4 flex flex-wrap gap-2">
<button type="button" onClick={reset} className={`film-reset border-stone-300 bg-white text-stone-800 hover:border-stone-900 ${btn}`}>
膜を戻す
</button>
<button
type="button"
onClick={makeShare}
disabled={busy}
className={`make-image border-stone-900 bg-stone-900 text-white hover:bg-stone-700 disabled:opacity-60 ${btn}`}
>
{busy ? "画像を作っています…" : "半分こすった画像を作る(1200×630)"}
</button>
</div>
{share && (
<figure className="mt-4 border border-stone-200 p-3">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={share} width={1200} height={630} alt="半分こすった福袋のカードと、伏せた価格の共有画像" className="h-auto w-full border border-stone-100" />
<figcaption className="mt-3 flex flex-wrap items-center justify-between gap-2 text-[13px] text-stone-600">
<span>SNSや告知に使える 1200×630 の画像です</span>
<a href={share} download="fukubukuro-scratch.png" className={`border-[#d97706] bg-white text-[#92400e] hover:bg-amber-50 ${btn}`}>
PNGを保存
</a>
</figcaption>
</figure>
)}
</div>
{/* 変える・持ち帰る(最初は畳む) */}
<div className="border-t border-stone-200 @[48rem]:col-start-2 @[48rem]:row-start-2 @[48rem]:self-start">
<details className="group border-b border-stone-200">
<summary className={`flex min-h-12 cursor-pointer list-none items-center justify-between gap-3 py-3 text-[15px] font-bold [&::-webkit-details-marker]:hidden ${focusRing}`}>
中身・価格・膜の色を変える
<span aria-hidden="true" className="text-stone-500 transition-transform duration-150 group-open:rotate-90 motion-reduce:transition-none">
▸
</span>
</summary>
<div className="pb-5">
<fieldset>
<legend className="text-[13px] font-bold text-stone-700">中身(5品)</legend>
<ol className="mt-2 grid gap-2">
{items.map((it, i) => (
<li key={i} className="grid grid-cols-[6.5rem_minmax(0,1fr)] gap-1.5 @[30rem]:grid-cols-[5.5rem_minmax(0,1fr)_6.5rem]">
<label className="sr-only" htmlFor={`${uid}-i${i}`}>{`${i + 1}品目のアイコン`}</label>
<select
id={`${uid}-i${i}`}
value={it.icon}
onChange={(e) => setItem(i, { icon: e.target.value as IconKey })}
className={`min-h-11 border border-stone-300 bg-white px-2 text-[14px] ${focusRing}`}
>
{(Object.keys(ICONS) as IconKey[]).map((k) => (
<option key={k} value={k}>
{ICONS[k].label}
</option>
))}
</select>
<label className="sr-only" htmlFor={`${uid}-n${i}`}>{`${i + 1}品目の品名`}</label>
<input
id={`${uid}-n${i}`}
value={it.name}
maxLength={24}
onChange={(e) => setItem(i, { name: e.target.value })}
className={`order-first col-span-2 min-h-11 min-w-0 border border-stone-300 bg-white px-2.5 text-[14px] @[30rem]:order-none @[30rem]:col-span-1 ${focusRing}`}
/>
<label className="sr-only" htmlFor={`${uid}-p${i}`}>{`${i + 1}品目の定価(円)`}</label>
<input
id={`${uid}-p${i}`}
inputMode="numeric"
value={it.price.toString()}
onChange={(e) => setItem(i, { price: toPrice(e.target.value) })}
className={`min-h-11 min-w-0 border border-stone-300 bg-white px-2.5 text-right text-[14px] tabular-nums ${focusRing}`}
/>
</li>
))}
</ol>
</fieldset>
<div className="mt-4 flex flex-wrap items-end gap-x-6 gap-y-4">
<label className="grid gap-1.5 text-[13px] font-bold text-stone-700">
福袋の価格(円)
<input
inputMode="numeric"
value={price.toString()}
onChange={(e) => setPrice(toPrice(e.target.value))}
className={`min-h-11 w-32 border border-stone-300 bg-white px-2.5 text-right text-[15px] font-normal text-stone-900 tabular-nums ${focusRing}`}
/>
</label>
<fieldset>
<legend className="mb-1.5 text-[13px] font-bold text-stone-700">膜の色</legend>
<div className="flex">
{(Object.keys(FILMS) as FilmKey[]).map((k) => (
<label key={k} className="relative">
<input type="radio" name={`${uid}-film`} value={k} checked={film === k} onChange={() => setFilm(k)} className="peer sr-only" />
<span
className={`-ml-px flex min-h-11 cursor-pointer items-center gap-2 border px-3.5 text-[14px] font-bold peer-focus-visible:ring-2 peer-focus-visible:ring-[#d97706] peer-focus-visible:ring-offset-2 ${film === k ? "relative z-10 border-stone-900 bg-stone-900 text-white" : "border-stone-300 bg-white text-stone-800"}`}
>
<span aria-hidden="true" className="size-3.5 border border-black/20" style={{ background: FILMS[k].swatch }} />
{FILMS[k].label}
</span>
</label>
))}
</div>
</fieldset>
</div>
<p className="mt-3 text-[13px] leading-[1.7] text-stone-600">変えた中身・価格・色は、カードと下のコードの両方に入ります。</p>
</div>
</details>
<details className="group border-b border-stone-200">
<summary className={`flex min-h-12 cursor-pointer list-none items-center justify-between gap-3 py-3 text-[15px] font-bold [&::-webkit-details-marker]:hidden ${focusRing}`}>
このカードのコードをコピー(React・HTML+JS)
<span aria-hidden="true" className="text-stone-500 transition-transform duration-150 group-open:rotate-90 motion-reduce:transition-none">
▸
</span>
</summary>
<div className="pb-5">
<div role="tablist" aria-label="コードの形" className="flex border-b border-stone-200">
{(
[
["react", "React(TSX)"],
["html", "HTML+JS"],
] as const
).map(([k, label]) => (
<button
key={k}
type="button"
role="tab"
id={`${uid}-t-${k}`}
aria-selected={tab === k}
aria-controls={`${uid}-code`}
data-tab={k}
onClick={() => setTab(k)}
className={`-mb-px min-h-11 border-b-2 px-4 text-[14px] font-bold ${focusRing} ${tab === k ? "border-[#d97706] text-stone-900" : "border-transparent text-stone-500 hover:text-stone-800"}`}
>
{label}
</button>
))}
</div>
<div role="tabpanel" id={`${uid}-code`} aria-labelledby={`${uid}-t-${tab}`}>
<pre className="mt-3 max-h-72 overflow-auto bg-stone-950 p-4 text-[12px] leading-[1.7] text-stone-100" tabIndex={0}>
<code>{code}</code>
</pre>
<button type="button" onClick={copy} className={`copy-code mt-3 border-stone-900 bg-white text-stone-900 hover:bg-stone-100 ${btn}`}>
<Swap on={copied} idle={tab === "react" ? "React のコードをコピー" : "HTML+JS をコピー"} done="コピーしました ✓" />
</button>
</div>
</div>
</details>
</div>
{/* ほかの季節の部品 */}
<nav aria-label="ほかの季節の部品" className="@[48rem]:col-start-2 @[48rem]:row-start-3 @[48rem]:self-end">
<p className="text-[13px] font-bold text-stone-600">年末年始の商品ページに合わせて</p>
<ul className="mt-2 divide-y divide-stone-200 border-y border-stone-200 text-[14px]">
{RELATED.map((r) => (
<li key={r.href}>
<a href={r.href} className={`flex min-h-11 flex-col justify-center gap-0.5 py-2 hover:text-[#b45309] @[30rem]:flex-row @[30rem]:items-center @[30rem]:justify-between @[30rem]:gap-3 ${focusRing}`}>
<span className="font-bold">{r.title}</span>
<span className="text-[13px] text-stone-500 @[30rem]:text-right">{r.note}</span>
</a>
</li>
))}
</ul>
</nav>
</div>
<p aria-live="polite" className="sr-only">
{open ? `福袋の価格は${yen(price)}です。中身の定価合計は${yen(total)}。${savingNote(total, price)}` : ""}
</p>
</section>
);
}
Add to your project via shadcn CLI
npx shadcn@latest add https://designs.first-ch.com/r/fukubukuro-scratch-reveal.json