05トルシェタイルの迷路
同じタイル1枚をランダムな角度で置くだけで、マスを越えてつながる曲線ができます。
使いどころ404ページの背景、カード格子の後ろに敷く模様
rotatetransform-originsteps

<main class="stage">
<div class="tr is-demo" id="root">
<svg class="tr__art" id="art" viewBox="0 0 240 144" role="img" data-label="同じタイルをランダムな角度で敷いてつながった曲線の迷路、シード {n}"></svg>
<div class="tr__bar">
<p class="tr__seed">
<svg xmlns="http://www.w3.org/2000/svg" class="tr__ic" viewBox="0 0 256 256" aria-hidden="true"><g fill="currentColor"><path d="M216 64v128a24 24 0 0 1-24 24H64a24 24 0 0 1-24-24V64a24 24 0 0 1 24-24h128a24 24 0 0 1 24 24" opacity=".2"/><path d="M192 32H64a32 32 0 0 0-32 32v128a32 32 0 0 0 32 32h128a32 32 0 0 0 32-32V64a32 32 0 0 0-32-32m16 160a16 16 0 0 1-16 16H64a16 16 0 0 1-16-16V64a16 16 0 0 1 16-16h128a16 16 0 0 1 16 16ZM104 92a12 12 0 1 1-12-12a12 12 0 0 1 12 12m72 0a12 12 0 1 1-12-12a12 12 0 0 1 12 12m-72 72a12 12 0 1 1-12-12a12 12 0 0 1 12 12m36-36a12 12 0 1 1-12-12a12 12 0 0 1 12 12m36 36a12 12 0 1 1-12-12a12 12 0 0 1 12 12"/></g></svg>
シード <b id="num">7</b>
</p>
<button class="tr__btn" type="button" id="again">
<svg xmlns="http://www.w3.org/2000/svg" class="tr__ic" viewBox="0 0 256 256" aria-hidden="true"><g fill="currentColor"><path d="M107.14 98.8L128 128l-20.86 29.2A64 64 0 0 1 55.06 184H32V72h23.06a64 64 0 0 1 52.08 26.8m93.8-26.8a64 64 0 0 0-52.08 26.8L128 128l20.86 29.2a64 64 0 0 0 52.08 26.8H232V72Z" opacity=".2"/><path d="M237.66 178.34a8 8 0 0 1 0 11.32l-24 24a8 8 0 0 1-11.32-11.32L212.69 192h-11.75a72.12 72.12 0 0 1-58.59-30.15l-41.72-58.4A56.1 56.1 0 0 0 55.06 80H32a8 8 0 0 1 0-16h23.06a72.12 72.12 0 0 1 58.59 30.15l41.72 58.4A56.1 56.1 0 0 0 200.94 176h11.75l-10.35-10.34a8 8 0 0 1 11.32-11.32ZM143 107a8 8 0 0 0 11.16-1.86l1.2-1.67A56.1 56.1 0 0 1 200.94 80h11.75l-10.35 10.34a8 8 0 0 0 11.32 11.32l24-24a8 8 0 0 0 0-11.32l-24-24a8 8 0 0 0-11.32 11.32L212.69 64h-11.75a72.12 72.12 0 0 0-58.59 30.15l-1.2 1.67A8 8 0 0 0 143 107m-30 42a8 8 0 0 0-11.16 1.86l-1.2 1.67A56.1 56.1 0 0 1 55.06 176H32a8 8 0 0 0 0 16h23.06a72.12 72.12 0 0 0 58.59-30.15l1.2-1.67A8 8 0 0 0 113 149"/></g></svg>
<span class="tr__label">再生成</span>
</button>
<button class="tr__btn" type="button" id="copy" data-done="コピーしました">
<svg xmlns="http://www.w3.org/2000/svg" class="tr__ic" viewBox="0 0 256 256" aria-hidden="true"><g fill="currentColor"><path d="M216 40v128h-48V88H88V40Z" opacity=".2"/><path d="M216 32H88a8 8 0 0 0-8 8v40H40a8 8 0 0 0-8 8v128a8 8 0 0 0 8 8h128a8 8 0 0 0 8-8v-40h40a8 8 0 0 0 8-8V40a8 8 0 0 0-8-8m-56 176H48V96h112Zm48-48h-32V88a8 8 0 0 0-8-8H96V48h112Z"/></g></svg>
<span class="tr__label">SVGをコピー</span>
</button>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 트루셰 타일 미로 — 타일은 한 장뿐이고 난수가 정하는 것은 각도(0·90·180·270)밖에 없다.
// 미리보기 루프는 그 네 각도를 steps(1, end) 로 한 프레임에 딱 끊어 넘긴다 — 중간 각도를 거치면
// 곡선이 반투명하게 겹쳐 보이고 poster 가 유령 프레임으로 뽑힌다.
// 한 바퀴에 360도를 돌아 제자리로 오므로 루프 끝에서 튀지 않는다.
$duration: $dur-loop;
$easing: steps(1, end);
$color: $subject-ink;
@include stage($stage-paper);
.tr { display: grid; justify-items: center; gap: $sp-3; width: 100%; }
.tr__art { display: block; width: clamp(176px, 60vw, 320px); height: auto; }
// 타일이 도는 중심은 타일 자신의 한가운데다 (blog-demo 규칙 8) — fill-box 의 경계 상자는
// 사분원 두 개를 합쳐 정확히 24×24 가 되므로 그 50% 50% 가 곧 타일 중심이다
.tr__tile {
transform-box: fill-box;
transform-origin: 50% 50%;
fill: none;
stroke-width: 3;
stroke-linecap: round;
}
.tr__tile--a { stroke: $color; }
.tr__tile--b { stroke: $subject-blue; }
.tr__bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: $sp-2; }
.tr__seed {
margin: 0;
display: inline-flex; align-items: center; gap: $sp-1;
color: rgba(23, 20, 26, .72);
font-weight: 700; font-size: clamp(9px, 2.4vw, 11px);
}
.tr__btn {
display: inline-flex; align-items: center; gap: $sp-1;
border: 0; border-radius: $r-pill;
padding: $sp-1 $sp-3;
background: $subject-ink; color: $subject-cream;
font-family: inherit; font-weight: 700; font-size: clamp(9px, 2.4vw, 11px);
cursor: pointer;
}
.tr__btn:focus-visible { outline: 3px solid $subject-blue; outline-offset: 2px; }
.tr__ic { width: 12px; height: 12px; flex: none; }
// ── 미리보기 루프: 뒤집기가 왼쪽 칸부터 차례로 번져 나간다.
// 시차는 타일 60장이 서로 다른 순간에 뒤집히도록 33ms 로 잡았다 — 대각선 번호(0~14)로 묶어
// 64ms 를 주면 같은 번호의 네 장이 한꺼번에 뒤집혀 이음매(마지막 프레임 → 첫 프레임) 한 칸에만
// 뒤집기가 몰린다. 실측: 이음매 7.197% · 보통 칸 최대 4.169% (run/293/_이음매.json)
.tr.is-demo .tr__tile {
animation-name: trFlip;
animation-duration: $duration;
animation-timing-function: $easing;
animation-iteration-count: infinite;
animation-fill-mode: backwards;
animation-delay: calc(var(--i) * -33ms); // 음수 지연이라 첫 프레임부터 뒤집기가 이미 번져 있다
}
// 사람이 「다시 생성」을 누르면 새 시드의 타일이 한 줄씩 내려앉는다
.tr.is-draw .tr__tile {
animation-name: trDrop;
animation-duration: $dur-enter;
animation-timing-function: $ease-pop;
animation-iteration-count: 1;
animation-fill-mode: backwards;
animation-delay: calc(var(--i) * 9ms);
}
@keyframes trFlip {
0% { transform: rotate(0deg); }
25% { transform: rotate(90deg); }
50% { transform: rotate(180deg); }
75% { transform: rotate(270deg); }
100% { transform: rotate(360deg); }
}
@keyframes trDrop {
from { transform: scale(.3); opacity: 0; }
to { transform: scale(1); opacity: 1; }
}
@media (max-width: 340px) {
.tr { gap: $sp-2; }
.tr__ic { width: 10px; height: 10px; }
}
@media (prefers-reduced-motion: reduce) {
.tr.is-demo .tr__tile,
.tr.is-draw .tr__tile { animation: none !important; transform: rotate(0deg) !important; }
}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);
}
.tr {
display: grid;
justify-items: center;
gap: 12px;
width: 100%;
}
.tr__art {
display: block;
width: clamp(176px, 60vw, 320px);
height: auto;
}
.tr__tile {
transform-box: fill-box;
transform-origin: 50% 50%;
fill: none;
stroke-width: 3;
stroke-linecap: round;
}
.tr__tile--a {
stroke: #17141a;
}
.tr__tile--b {
stroke: #2f6df6;
}
.tr__bar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 8px;
}
.tr__seed {
margin: 0;
display: inline-flex;
align-items: center;
gap: 4px;
color: rgba(23, 20, 26, 0.72);
font-weight: 700;
font-size: clamp(9px, 2.4vw, 11px);
}
.tr__btn {
display: inline-flex;
align-items: center;
gap: 4px;
border: 0;
border-radius: 999px;
padding: 4px 12px;
background: #17141a;
color: #fff7e6;
font-family: inherit;
font-weight: 700;
font-size: clamp(9px, 2.4vw, 11px);
cursor: pointer;
}
.tr__btn:focus-visible {
outline: 3px solid #2f6df6;
outline-offset: 2px;
}
.tr__ic {
width: 12px;
height: 12px;
flex: none;
}
.tr.is-demo .tr__tile {
animation-name: trFlip;
animation-duration: 2s;
animation-timing-function: steps(1, end);
animation-iteration-count: infinite;
animation-fill-mode: backwards;
animation-delay: calc(var(--i) * -33ms);
}
.tr.is-draw .tr__tile {
animation-name: trDrop;
animation-duration: 600ms;
animation-timing-function: cubic-bezier(0.2, 1.4, 0.4, 1);
animation-iteration-count: 1;
animation-fill-mode: backwards;
animation-delay: calc(var(--i) * 9ms);
}
@keyframes trFlip {
0% {
transform: rotate(0deg);
}
25% {
transform: rotate(90deg);
}
50% {
transform: rotate(180deg);
}
75% {
transform: rotate(270deg);
}
100% {
transform: rotate(360deg);
}
}
@keyframes trDrop {
from {
transform: scale(0.3);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}
}
@media (max-width: 340px) {
.tr {
gap: 8px;
}
.tr__ic {
width: 10px;
height: 10px;
}
}
@media (prefers-reduced-motion: reduce) {
.tr.is-demo .tr__tile,
.tr.is-draw .tr__tile {
animation: none !important;
transform: rotate(0deg) !important;
}
}var root = document.getElementById('root');
var art = document.getElementById('art');
var num = document.getElementById('num');
var SIZE = 24, COLS = 10, ROWS = 6;
// 타일 한 장 = 이웃한 두 변의 한가운데를 잇는 사분원 두 개. 이것만 있으면 된다
// (왼쪽 변 중점 → 위쪽 변 중점, 오른쪽 변 중점 → 아래쪽 변 중점. 마주 보는 변끼리면 사분원이 안 된다)
var TILE = 'M0 12A12 12 0 0 1 12 0M24 12A12 12 0 0 0 12 24';
var seed = 7;
// mulberry32 — 32비트 정수 シード 하나로 언제나 같은 난수열을 돌려준다. 재현 가능한 생성의 뿌리
function mulberry32(a) {
return function () {
a = a + 0x6D2B79F5 | 0;
var t = Math.imul(a ^ a >>> 15, 1 | a);
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
return ((t ^ t >>> 14) >>> 0) / 4294967296;
};
}
function build() {
var rand = mulberry32(seed), parts = [], col, row;
for (row = 0; row < ROWS; row++) {
for (col = 0; col < COLS; col++) {
var turn = Math.floor(rand() * 4) * 90;
var tone = rand() < 0.28 ? 'b' : 'a';
// 바깥 g 는 자리만 잡는다(정적). 애니메이션이 붙는 안쪽 g 에 CSS transform 을 쓰면
// transform 속성이 덮여 타일이 제자리를 잃기 때문이다
parts.push('<g transform="translate(' + col * SIZE + ' ' + row * SIZE + ')">' +
'<g class="tr__tile tr__tile--' + tone + '" style="--i:' + (col * ROWS + row) + '">' +
'<path transform="rotate(' + turn + ' 12 12)" d="' + TILE + '"/></g></g>');
}
}
art.innerHTML = parts.join('');
art.setAttribute('aria-label', art.getAttribute('data-label').replace('{n}', seed));
num.textContent = seed;
}
document.getElementById('again').addEventListener('click', function () {
seed = (seed * 7 + 13) % 991 + 1;
build();
root.classList.remove('is-demo');
root.classList.remove('is-draw');
void art.getBoundingClientRect().width; // 한 번 읽어 리플로를 일으켜야 같은 애니메이션이 처음부터 다시 돈다
root.classList.add('is-draw');
});
var copyBtn = document.getElementById('copy');
copyBtn.addEventListener('click', function () {
var label = copyBtn.querySelector('.tr__label');
var before = label.textContent;
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(art.outerHTML).catch(function () {});
}
label.textContent = copyBtn.getAttribute('data-done');
setTimeout(function () { label.textContent = before; }, 1200);
});
build();// TruchetTiles — vanilla 판(run/293/demo/05-generative-truchet-tiles/index.html) 의 React 포트.
// 타일은 한 장뿐이고 난수가 정하는 것은 각도(0·90·180·270)와 색 두 가지밖에 없다.
// 시드·격자 수·확률(0.28)은 vanilla 와 같은 값이다.
import { useMemo, useRef, useState } from "react";
import type { CSSProperties } from "react";
import styles from "./TruchetTiles.module.scss";
export type TruchetTilesProps = {
duration?: number;
easing?: string;
color?: string;
label?: string;
seedText?: string;
regenerateText?: string;
copyText?: string;
copiedText?: string;
};
type Vars = CSSProperties & { "--duration"?: string; "--easing"?: string; "--color"?: string };
// useRef 는 T | null 을 돌려준다. 처음부터 값이 있고 절대 비지 않는 상자는 이렇게 좁혀 쓴다
type Box<T> = { current: T };
type Tile = { x: number; y: number; turn: number; toned: boolean; i: number };
const SIZE = 24;
const COLS = 10;
const ROWS = 6;
const W = SIZE * COLS;
const H = SIZE * ROWS;
// 타일 한 장 = 이웃한 두 변의 한가운데를 잇는 사분원 두 개. 이것만 있으면 된다
// (왼쪽 변 중점 → 위쪽 변 중점, 오른쪽 변 중점 → 아래쪽 변 중점. 마주 보는 변끼리면 사분원이 안 된다)
const TILE = "M0 12A12 12 0 0 1 12 0M24 12A12 12 0 0 0 12 24";
// mulberry32 — 32비트 정수 시드 하나로 언제나 같은 난수열을 돌려준다. 재현 가능한 생성의 뿌리
function mulberry32(a: number): () => number {
return function (): number {
a = a + 0x6D2B79F5 | 0;
let t = Math.imul(a ^ a >>> 15, 1 | a);
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
return ((t ^ t >>> 14) >>> 0) / 4294967296;
};
}
// 난수를 부르는 차례(각도 → 색)가 vanilla 와 같아야 같은 시드에서 같은 미로가 나온다
function build(s: number): Tile[] {
const rand = mulberry32(s);
const out: Tile[] = [];
for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
const turn = Math.floor(rand() * 4) * 90;
const toned = rand() < 0.28;
out.push({ x: col * SIZE, y: row * SIZE, turn: turn, toned: toned, i: col + row });
}
}
return out;
}
export default function TruchetTiles({
duration = 2000,
easing = "steps(1, end)",
color = "#17141a",
label = "A maze of curves from one tile laid at random angles, seed {n}",
seedText = "Seed",
regenerateText = "Regenerate",
copyText = "Copy SVG",
copiedText = "Copied",
}: TruchetTilesProps) {
const artRef = useRef<SVGSVGElement | null>(null);
const timerRef = useRef<number>(0) as Box<number>;
const [seed, setSeed] = useState(7);
const [mode, setMode] = useState("demo");
const [copyLabel, setCopyLabel] = useState(copyText);
const vars: Vars = { "--duration": `${duration}ms`, "--easing": easing, "--color": color };
// 시드가 바뀔 때만 다시 계산한다 — 같은 시드면 언제나 같은 타일 배열이 나온다
const tiles = useMemo(() => build(seed), [seed]);
function regenerate(): void {
setSeed((prev: number) => (prev * 7 + 13) % 991 + 1);
setMode("draw");
}
function copySvg(): void {
const art = artRef.current;
if (!art) { return; }
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(art.outerHTML).catch(function () {});
}
setCopyLabel(copiedText);
clearTimeout(timerRef.current);
timerRef.current = window.setTimeout(() => setCopyLabel(copyText), 1200);
}
const rootClass = `${styles.tr} ${mode === "demo" ? styles.isDemo : styles.isDraw}`;
return (
<div className={rootClass} style={vars}>
<svg
ref={artRef}
className={styles.art}
viewBox={`0 0 ${W} ${H}`}
role="img"
aria-label={label.replace("{n}", String(seed))}
>
{/* 바깥 g 는 자리만 잡는다(정적). 애니메이션이 붙는 안쪽 g 에 CSS transform 을 쓰면
transform 속성이 덮여 타일이 제자리를 잃기 때문이다 */}
{tiles.map((t: Tile, k: number) => (
<g key={k} transform={`translate(${t.x} ${t.y})`}>
<g
className={`${styles.tile} ${t.toned ? styles.toneB : styles.toneA}`}
style={{ "--i": t.i } as CSSProperties}
>
<path transform={`rotate(${t.turn} 12 12)`} d={TILE} />
</g>
</g>
))}
</svg>
<div className={styles.bar}>
<p className={styles.seed}>{seedText} <b>{seed}</b></p>
<button className={styles.btn} type="button" onClick={regenerate}>{regenerateText}</button>
<button className={styles.btn} type="button" onClick={copySvg}>{copyLabel}</button>
</div>
</div>
);
}05 トルシェタイルの迷路 — 計測 累積面積 26.122% · 動いたフレーム 22/23GODRICH オリジナル · SCSS と React は zip に同梱 · css 背景 パターン ジェネレーター 自作9種
このデモが属する記事
css 背景 パターン ジェネレーター 自作9種css 背景 パターン ジェネレーターは、画像ファイルを配る代わりに数字ひとつから模様をその場で計算する仕組みです。ここで紹介する9つはシードひとつで絵が決まり、同じ数字を入れ直せば同じ絵が必ず戻ってきます。 この記事のデモをすべて見る


