Lab · 2026-11-24

글자로 달리는 서울, HONNE 'B I K E' 오마주

HONNE 'B I K E' 뮤비의 자전거 탄 두 사람이 남산에서 경복궁, 한강 철교를 건너는 2호선을 지나 잠실 롯데월드타워까지 달려요. 브라우저가 매 프레임 장면을 그린 뒤 8×12 칸마다 글자 하나로 바꿔요. 사람은 칸 무늬와 가장 닮은 글자, 배경은 밝기 글자와 윤곽선 글자로 찍어요. 원곡: HONNE - B I K E. 영상은 @ai.asap.kr 릴스에 있어요.

글자로 달리는 서울, HONNE 'B I K E' 오마주 릴스 표지
HTML·그림 묶음 받기브라우저에서 바로 보기

HTML 파일 한 개, 404줄. lab 폴더의 그림 13장과 함께 열어야 해요(묶음 받기).

광고

코드

클로드와 짠 코드예요. 두 사람은 원본 뮤비 그림을 오린 147장(한 바퀴), 배경·랜드마크는 이미지 생성 그림이고, 장면을 그리고 글자로 바꾸는 건 아래 코드가 브라우저에서 해요. 릴스 영상도 이 코드를 그대로 녹화한 거예요.

광고
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>bike_ascii.js</title>
<style>
body{margin:0;height:100vh;background:#000;display:grid;place-items:center;overflow:hidden;font-family:system-ui,sans-serif}
canvas{width:min(100vw,56.25vh)}
#go{position:fixed;inset:0;display:grid;place-items:center;color:#c8ccd4;background:#000;font-size:15px}
</style>
</head>
<body>
<canvas id="view" width="1080" height="1920"></canvas>
<div id="go">그림 불러오는 중…</div>
<script>
(async () => {
// bike_ascii.js : two friends ride a bike across Seoul, Namsan -> Gyeongbokgung -> Line 2 over the Han -> Lotte World Tower
// every frame is painted on a hidden canvas, then each 8x12 cell becomes one letter
const SOURCE = document.currentScript.text.replace(/^\n+/, '').trimEnd().split('\n');

// ---- layout ----
const W = 1080, H = 1920, ART_H = 1200, CW = 8, CH = 12;
const COLS = W / CW, ROWS = ART_H / CH, CELLS = COLS * ROWS;
const CODE_TOP = 1300, CODE_ROWS = 18, LINE_H = 30, FPS = 25, DUR = 90;
const HORIZON = 880, ROAD_TOP = 1000, ROAD_BOT = 1072, SPEED = 430;      // px per second along the path
const CROP = [90, 262, 810, 900];                                         // camera: this part of the scene fills the frame
const P_MOUNT = 0.10, P_CITY = 0.22, P_MARK = 0.34, P_MID = 0.72;         // parallax: far things move slower
const BG = [5, 7, 13];
const RAMP = " .':;~^+=*xvo%&#W@";              // background: brightness order, soft marks -> dense letters
const EDGE = "-\\|/";                             // background edges: a line letter that follows the edge
const FIG = " .,:;'`-_~^=+*<>!/\\|()[]{}ivxoOX0#%&@";   // riders: the letter whose shape best fits the cell

const dist = t => SPEED * t;
const at = (p, t, sx) => sx + p * dist(t);                                // where a landmark sits so it is at sx at time t
const MARKS = [["namsan", at(P_MARK, 3.5, 660)], ["palace", at(P_MARK, 30.5, 690)], ["lotte", at(P_MARK, 87, 790)]];
const P_RIV = 0.6;                                                         // the Han and its railway bridge: between the trees and the far city
const SPAN = [69, 650], SPAN_W = SPAN[1] - SPAN[0], TILES = 15;           // one bridge span = pier to pier, repeated
const B0 = 1220 + P_RIV * dist(45), B1 = B0 + TILES * SPAN_W;           // the bridge comes in from the right at 45 s, leaves at ~84 s
const RIVER = [B0 - 120, B1 + 160];                                       // water a little wider than the bridge on both ends
const TRAINS = [44, 57, 70];                                              // Line 2 trains enter the bridge's right end at these seconds

// sky through the day: [time, top colour, horizon colour, light on things, night]
const SKY = [
  [0, [214, 96, 140], [255, 170, 120], [0.95, 0.88, 0.88], 0.1], [12, [232, 92, 108], [255, 184, 96], [0.98, 0.9, 0.85], 0],
  [30, [238, 104, 74], [255, 206, 92], [1.0, 0.93, 0.85], 0], [60, [244, 118, 78], [255, 218, 110], [1.0, 0.95, 0.88], 0],
  [76, [236, 86, 84], [255, 176, 76], [1.0, 0.9, 0.8], 0], [85, [210, 70, 100], [255, 140, 70], [0.95, 0.82, 0.78], 0.1],
  [90, [160, 60, 110], [250, 120, 80], [0.85, 0.72, 0.74], 0.3]];
// each line in its own colour, like the hand-lettered lyrics in the music video (lifted a little to read on a dark sky)
const LYRICS = [
  [15.0, 17.6, "Early morning Saturday", [120, 120, 255]], [18.5, 20.9, "Birds are calling out my name", [255, 90, 90]],
  [21.0, 23.9, "And they're telling me to leave my bed", [120, 225, 110]], [24.0, 26.9, "Drink a coffee for my head", [255, 236, 130]],
  [28.0, 30.4, "Cereal and radio", [255, 110, 180]], [31.4, 33.9, "Mr sun saying \"hello\"", [140, 235, 100]],
  [34.0, 36.9, "And I pick some clothes from my wardrobe", [170, 130, 255]], [37.4, 39.4, "Get the bike from out the shed", [255, 225, 200]],
  [40.0, 42.9, "Let the wheels go round and round", [120, 120, 255]], [43.0, 46.4, "I'm pulling up at your house", [255, 90, 90]],
  [46.5, 49.9, "And I say nervously", [130, 220, 110]], [50.9, 52.9, "\"Come and take a ride with me\"", [255, 236, 210]],
  [54.4, 57.4, "I like like riding my bike", [255, 110, 180]], [58.0, 60.9, "You behind holding me tight", [140, 235, 100]],
  [61.0, 63.4, "Ain't nothing ever felt so right", [170, 130, 255]], [63.5, 65.9, "With you I could do this all day", [120, 120, 255]],
  [67.4, 70.4, "I like the sun on my face", [255, 90, 90]], [70.9, 73.9, "Feeling your hands on my waist", [130, 220, 110]],
  [74.4, 76.4, "Ain't nothing ever felt so right", [255, 236, 210]], [76.5, 79.4, "With you I could do this all day", [255, 110, 180]],
  [83.9, 86.4, "Won't you come and take a ride with me?", [140, 235, 100]]];

const clamp = (v, a = 0, b = 1) => Math.min(b, Math.max(a, v));
const ease = x => { x = clamp(x); return x * x * (3 - 2 * x); };
const lerp = (a, b, k) => a + (b - a) * k;
const mix = (a, b, k) => a.map((v, i) => lerp(v, b[i], k));
function skyAt(t) {
  for (let i = 0; i < SKY.length - 1; i++) if (t <= SKY[i + 1][0]) {
    const [a, ...va] = SKY[i], [b, ...vb] = SKY[i + 1], k = ease((t - a) / (b - a));
    return [mix(va[0], vb[0], k), mix(va[1], vb[1], k), mix(va[2], vb[2], k), lerp(va[3], vb[3], k)];
  }
  return SKY[SKY.length - 1].slice(1);
}
const rgb = c => `rgb(${c[0] | 0},${c[1] | 0},${c[2] | 0})`;

// ---- pictures: painted strips and landmarks (made with an image model), and one loop of the riders ----
const load = src => new Promise((ok, no) => { const i = new Image(); i.onload = () => ok(i); i.onerror = no; i.src = src; });
const NAMES = ["hills", "city", "trees", "road", "leaves", "namsan", "palace", "lotte", "bridge", "train", "riders0", "riders1", "riders2"];
const DIR = location.pathname.endsWith('/code/') ? '../lab/' : 'lab/';  // on the site this page lives at .../code/, the pictures one level up
const IMG = Object.fromEntries(await Promise.all(NAMES.map(async n => [n, await load(`${DIR}${n}.webp`)])));
const RIDER = { w: 960, h: 864, cols: 7, per: 49, n: 147, scale: 1 };      // 147 frames = one pedal loop, full size, 3 sheets of 7x7
const FRAMES = await Promise.all(Array.from({ length: RIDER.n }, (_, k) => {  // cut the sheets once: one picture per frame
  const s = IMG['riders' + Math.floor(k / RIDER.per)], j = k % RIDER.per;
  return createImageBitmap(s, (j % RIDER.cols) * RIDER.w, Math.floor(j / RIDER.cols) * RIDER.h, RIDER.w, RIDER.h);
}));

// a "weight" copy of a picture: same outline, filled with one grey = how densely to letter it
function silhouette(img, w) {
  const c = new OffscreenCanvas(img.width, img.height), x = c.getContext('2d');
  x.drawImage(img, 0, 0); x.globalCompositeOperation = 'source-in';
  x.fillStyle = `rgb(${w * 255 | 0},${w * 255 | 0},${w * 255 | 0})`; x.fillRect(0, 0, c.width, c.height);
  return c;
}
const WEIGHT = { hills: 0.32, city: 0.42, trees: 0.38, road: 0.38, leaves: 1, namsan: 1, palace: 1, lotte: 1, bridge: 1, train: 1 };
const SIL = Object.fromEntries(Object.keys(WEIGHT).map(n => [n, silhouette(IMG[n], WEIGHT[n])]));
const RS = new OffscreenCanvas(COLS, ROWS), rs = RS.getContext('2d');      // the riders' outline, one pixel per cell
const RC = new OffscreenCanvas(RIDER.w, RIDER.h), rc = RC.getContext('2d'); // one rider frame, tinted

// ---- painting one moment ----
const S = new OffscreenCanvas(W, ART_H), sc = S.getContext('2d');           // the scene before the camera crop
const SW = new OffscreenCanvas(W, ART_H), sw = SW.getContext('2d');         // its weight map
const F = new OffscreenCanvas(W, ART_H), fc = F.getContext('2d');           // final picture
const FW = new OffscreenCanvas(COLS, ROWS), fw = FW.getContext('2d', { willReadFrequently: true }); // final weights, one pixel per cell
const FM = new OffscreenCanvas(COLS, ROWS), fm = FM.getContext('2d', { willReadFrequently: true }); // where the riders are, one pixel per cell
fw.setTransform(1 / CW, 0, 0, 1 / CH, 0, 0); fm.setTransform(1 / CW, 0, 0, 1 / CH, 0, 0);
const STARS = Array.from({ length: 260 }, (_, i) => [((i * 0.618034) % 1), ((i * 0.381966 * 7) % 1), (i * 0.7548) % 1]);

function strip(ctx, wctx, name, bottom, offset, tint) {                    // repeat a strip across the width
  const im = IMG[name], h = im.height, tw = im.width, y = bottom - h;
  for (let x = -(offset % tw); x < W; x += tw) {
    ctx.drawImage(im, x, y); if (wctx) wctx.drawImage(SIL[name], x, y);
  }
  if (tint) { ctx.save(); ctx.globalCompositeOperation = 'source-atop'; ctx.fillStyle = tint; ctx.fillRect(0, y, W, h); ctx.restore(); }
}

// sky texture made once: long horizontal brush streaks + soft blotches + grain, like a hand-painted sky
const SKYTEX = (() => {
  const c = new OffscreenCanvas(W, ART_H), x = c.getContext('2d');
  x.fillStyle = '#808080'; x.fillRect(0, 0, W, ART_H);
  let seed = 7; const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
  for (let k = 0; k < 900; k++) {                                          // streaks
    const y = rnd() * ART_H, x0 = rnd() * W - 200, len = 120 + rnd() * 520, h = 3 + rnd() * 10, v = 128 + (rnd() - 0.5) * 90;
    x.fillStyle = `rgba(${v | 0},${v | 0},${v | 0},${0.25 + rnd() * 0.35})`;
    x.beginPath(); x.ellipse(x0 + len / 2, y, len / 2, h / 2, (rnd() - 0.5) * 0.08, 0, 7); x.fill();
  }
  for (let k = 0; k < 60; k++) {                                           // blotches
    const v = 128 + (rnd() - 0.5) * 70, r = 60 + rnd() * 160, cx = rnd() * W, cy = rnd() * ART_H;
    const g = x.createRadialGradient(cx, cy, 0, cx, cy, r);
    g.addColorStop(0, `rgba(${v | 0},${v | 0},${v | 0},0.35)`); g.addColorStop(1, `rgba(${v | 0},${v | 0},${v | 0},0)`);
    x.fillStyle = g; x.fillRect(cx - r, cy - r, r * 2, r * 2);
  }
  return c;
})();
// 4x4 ordered dither: neighbouring cells of the same brightness get slightly different letters, so a smooth sky never turns into rows of vvvv / xxxx
const BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5].map(v => (v + 0.5) / 16 - 0.5);

function paint(t) {
  const [top, hor, light, night] = skyAt(t);
  // sky: a bright sunset like the music video — pink-red at the top, orange-yellow at the horizon (stars only once it gets dark)
  const g = sc.createLinearGradient(0, 0, 0, HORIZON);
  for (let k = 0; k <= 8; k++) { const y = k / 8, m = y ** 1.3, b = 1 - 0.55 * night * (1 - m); g.addColorStop(y, rgb(mix(top, hor, m).map(v => v * b))); }
  sc.fillStyle = g; sc.fillRect(0, 0, W, ART_H);
  sc.save(); sc.globalCompositeOperation = 'overlay'; sc.globalAlpha = 0.55; sc.drawImage(SKYTEX, (-dist(t) * 0.03) % W, 0); sc.drawImage(SKYTEX, (-dist(t) * 0.03) % W + W, 0); sc.restore();
  sw.fillStyle = 'rgb(190,190,190)'; sw.fillRect(0, 0, W, ART_H);            // sky weight 0.75: the sky is full of letters, as in the video
  if (night > 0.3) {
    sc.fillStyle = `rgba(255,255,255,${(night - 0.3) * 0.9})`;
    for (const [a, b, c] of STARS) sc.fillRect(a * W | 0, b * HORIZON * 0.7 | 0, 3, 3 * (0.3 + 0.7 * c));
  }
  // far hills and city, then the landmarks
  const shade = `rgba(${hor.map(v => v | 0)},0.2)`;
  strip(sc, sw, "hills", HORIZON + 12, P_MOUNT * dist(t), shade);
  strip(sc, sw, "city", HORIZON + 12, P_CITY * dist(t), null);
  for (const [n, x0] of MARKS) {
    const im = IMG[n], x = x0 - P_MARK * dist(t) - im.width / 2;
    if (x > -im.width && x < W) { sc.drawImage(im, x, HORIZON + 12 - im.height); sw.drawImage(SIL[n], x, HORIZON + 12 - im.height); }
  }
  // the Han river (far water, then a railing near the path)
  const ra = Math.max(0, RIVER[0] - P_RIV * dist(t)), rb = Math.min(W, RIVER[1] - P_RIV * dist(t));
  if (rb > 0 && ra < W) {
    sc.fillStyle = rgb(hor.map(v => v * 0.55)); sc.fillRect(ra, HORIZON + 10, rb - ra, ROAD_TOP - HORIZON - 10);
    sc.fillStyle = rgb(hor.map(v => Math.min(255, v * 0.95 + 30)));
    for (let k = 0; k < 70; k++) {
      const y = HORIZON + 16 + (k % 10) * 11, x = ((k * 97.3 - dist(t) * 0.55 + 40 * Math.sin(t * 1.3 + k)) % (W + 200) + W + 200) % (W + 200) - 100;
      if (x > ra && x < rb) sc.fillRect(x, y, 18 + (k % 7) * 3, 2);
    }
  }
  // the railway bridge: one long row of spans; trains run along it from right to left
  const br = IMG.bridge, by = ROAD_TOP + 2 - br.height;
  const bl = B0 - P_RIV * dist(t), bre = B1 - P_RIV * dist(t);
  if (bre > 0 && bl < W) {
    const tr = IMG.train, ty = by + br.height * 0.31 - tr.height;
    sc.save(); sc.beginPath(); sc.rect(bl, 0, bre - bl, ART_H); sc.clip();
    for (const t0 of TRAINS) {
      const tx = bre - (t - t0) * 300;                                       // front of the train, 300 px/s along the bridge
      if (tx < bre && tx + tr.width > bl) { sc.drawImage(tr, tx, ty); sw.drawImage(SIL.train, tx, ty); }
    }
    sc.restore();
    for (let k = 0; k < TILES; k++) {
      const x = bl + k * SPAN_W;
      if (x + SPAN_W < 0 || x > W) continue;
      sc.drawImage(br, SPAN[0], 0, SPAN_W, br.height, x, by, SPAN_W, br.height);
      sw.drawImage(SIL.bridge, SPAN[0], 0, SPAN_W, br.height, x, by, SPAN_W, br.height);
    }
  }
  strip(sc, sw, "trees", ROAD_TOP + 4, P_MID * dist(t), null);
  // the path: dark grass below, the painted bike lane
  sc.fillStyle = rgb([6, 30, 12].map((v, i) => v * light[i])); sc.fillRect(0, ROAD_TOP, W, ART_H - ROAD_TOP);
  strip(sc, sw, "road", ROAD_BOT + 30, dist(t), null);
  // light of the hour over everything painted so far
  sc.save(); sc.globalCompositeOperation = 'multiply'; sc.fillStyle = rgb(light.map(v => v * 255)); sc.fillRect(0, HORIZON - 600, W, ART_H); sc.restore();

  // camera crop -> final frame; riders and the leaves in front go on top at full size
  const [cx, cy, cw, ch] = CROP;
  fc.drawImage(S, cx, cy, cw, ch, 0, 0, W, ART_H); fw.drawImage(SW, cx, cy, cw, ch, 0, 0, W, ART_H);
  fm.fillStyle = '#000'; fm.fillRect(0, 0, W, ART_H);
  fw.imageSmoothingQuality = fm.imageSmoothingQuality = 'high';
  const fr = FRAMES[Math.floor(t * FPS) % RIDER.n];
  const dw = RIDER.w * RIDER.scale, dh = RIDER.h * RIDER.scale, dx = -20, dy = 1056 - 870 * 0.96;
  rc.globalCompositeOperation = 'copy'; rc.drawImage(fr, 0, 0);            // riders take half of the hour's light
  rc.globalCompositeOperation = 'multiply'; rc.fillStyle = rgb(light.map(v => (0.55 + 0.45 * v) * 255)); rc.fillRect(0, 0, RIDER.w, RIDER.h);
  rc.globalCompositeOperation = 'destination-in'; rc.drawImage(fr, 0, 0);
  fc.drawImage(RC, dx, dy, dw, dh);
  rs.globalCompositeOperation = 'copy'; rs.drawImage(fr, dx / CW, dy / CH, dw / CW, dh / CH);
  rs.globalCompositeOperation = 'source-in'; rs.fillStyle = '#fff'; rs.fillRect(0, 0, COLS, ROWS);
  fw.save(); fw.resetTransform(); fw.drawImage(RS, 0, 0); fw.restore();
  fm.save(); fm.resetTransform(); fm.drawImage(RS, 0, 0); fm.restore();
  const lv = IMG.leaves;
  for (let x = -((1.7 * dist(t)) % lv.width); x < W; x += lv.width) {
    fc.drawImage(lv, x, ART_H - lv.height); fw.drawImage(SIL.leaves, x, ART_H - lv.height); fm.drawImage(SIL.leaves, x, ART_H - lv.height);
  }
  fc.save(); fc.globalCompositeOperation = 'multiply'; fc.fillStyle = rgb(light.map(v => v * 255));   // leaves in the hour's light
  fc.fillRect(0, ART_H - lv.height, W, lv.height); fc.restore();
}

// ---- letters ----
function atlas(chars) {
  const c = new OffscreenCanvas(CW, CH), x = c.getContext('2d', { willReadFrequently: true });
  return Array.from(chars, ch => {
    x.fillStyle = '#000'; x.fillRect(0, 0, CW, CH);
    x.fillStyle = '#fff'; x.font = '12px Menlo, Consolas, monospace'; x.textAlign = 'center'; x.textBaseline = 'middle';
    x.fillText(ch, CW / 2, CH / 2 + 0.5);
    const d = x.getImageData(0, 0, CW, CH).data, g = new Float32Array(CW * CH);
    for (let i = 0; i < g.length; i++) g[i] = d[i * 4] / 255;
    return g;
  });
}
const A_RAMP = atlas(RAMP), A_EDGE = atlas(EDGE), A_FIG = atlas(FIG);
const FIG_C = A_FIG.map(g => { const m = g.reduce((a, b) => a + b) / g.length, c = g.map(v => v - m), n = Math.hypot(...c) + 1e-6;
  return { c: c.map(v => v / n), cov: m }; });
const COVMAX = Math.max(...FIG_C.map(f => f.cov));
const view = document.getElementById('view'), ctx = view.getContext('2d'), out = ctx.createImageData(W, ART_H);
const Lraw = new Float32Array(CELLS), Lc = new Float32Array(CELLS), Le = new Float32Array(CELLS);
const Wc = new Float32Array(CELLS), Fc = new Float32Array(CELLS), col = new Float32Array(CELLS * 3);
const letter = new Int16Array(CELLS), kind = new Int8Array(CELLS), P = new Float32Array(CW * CH);

function percentile(vals, n, p) {
  const h = new Uint32Array(256); for (let i = 0; i < n; i++) h[Math.min(255, vals[i] * 255 | 0)]++;
  for (let i = 0, k = 0; i < 256; i++) { k += h[i]; if (k >= n * p) return i / 255; }
  return 1;
}

function letters() {
  // one rule for the whole frame, the same as our HONNE 'B I K E' ASCII:
  //   brightness stretched between this frame's 1% and 99.5% pixels, then for every 8x12 cell the letter whose
  //   shape best fits the cell's pattern (density + normalised correlation); colour = the cell's brightest pixel
  const px = fc.getImageData(0, 0, W, ART_H).data;
  const lum = new Float32Array(W * ART_H), h = new Uint32Array(256);
  for (let i = 0, j = 0; i < W * ART_H; i++, j += 4) { const v = (0.2126 * px[j] + 0.7152 * px[j + 1] + 0.0722 * px[j + 2]) / 255; lum[i] = v; h[Math.min(255, v * 255 | 0)]++; }
  let lo = 0, hi = 1;
  for (let i = 0, k = 0; i < 256; i++) { k += h[i]; if (k >= lum.length * 0.01) { lo = i / 255; break; } }
  for (let i = 0, k = 0; i < 256; i++) { k += h[i]; if (k >= lum.length * 0.995) { hi = i / 255; break; } }
  const span = Math.max(hi - lo, 0.1);
  for (let i = 0; i < lum.length; i++) lum[i] = clamp((lum[i] - lo) / span) ** 0.85;   // a little lifted: our scene is darker than the original under its bright sky
  for (let r = 0; r < ROWS; r++) for (let c = 0; c < COLS; c++) {
    const i = r * COLS + c; let m = 0, best = -1, bj = 0;
    for (let y = 0; y < CH; y++) for (let x = 0; x < CW; x++) {
      const p = (r * CH + y) * W + c * CW + x, v = lum[p]; P[y * CW + x] = v; m += v;
      if (v > best) { best = v; bj = p * 4; }
    }
    m /= 96; Lc[i] = m;
    col[i * 3] = px[bj]; col[i * 3 + 1] = px[bj + 1]; col[i * 3 + 2] = px[bj + 2];
    let n = 0;
    for (let q = 0; q < 96; q++) { P[q] -= m; n += P[q] * P[q]; }
    const wShape = clamp((Math.sqrt(n / 96) - 0.05) * 6), nrm = Math.sqrt(n) + 1e-6;
    let bk = 0, bc = 1e9;
    for (let k = 0; k < FIG_C.length; k++) {
      const g = FIG_C[k]; let dot = 0;
      if (wShape > 0) for (let q = 0; q < 96; q++) dot += P[q] * g.c[q];
      const cost = ((g.cov - m * COVMAX) / COVMAX) ** 2 - 0.8 * wShape * dot / nrm;
      if (cost < bc) { bc = cost; bk = k; }
    }
    letter[i] = bk; kind[i] = 2;
  }
  const d = out.data; let count = 0;
  for (let r = 0; r < ROWS; r++) for (let c = 0; c < COLS; c++) {
    const i = r * COLS + c, g = kind[i] === 2 ? A_FIG[letter[i]] : kind[i] === 1 ? A_EDGE[letter[i]] : A_RAMP[letter[i]];
    let R = col[i * 3], G = col[i * 3 + 1], B = col[i * 3 + 2];
    const m = (R + G + B) / 3; R = m + (R - m) * 1.3; G = m + (G - m) * 1.3; B = m + (B - m) * 1.3;   // a bit more saturated
    const s = 255 * (0.62 + 0.38 * Math.sqrt(Lc[i])) / Math.max(R, G, B, 1);
    R = clamp(R * s, 0, 255); G = clamp(G * s, 0, 255); B = clamp(B * s, 0, 255);
    if (letter[i] || kind[i]) count++;
    for (let y = 0; y < CH; y++) for (let x = 0; x < CW; x++) {
      const a = g[y * CW + x], o = ((r * CH + y) * W + c * CW + x) * 4;
      d[o] = BG[0] + a * (R - BG[0]); d[o + 1] = BG[1] + a * (G - BG[1]); d[o + 2] = BG[2] + a * (B - BG[2]); d[o + 3] = 255;
    }
  }
  ctx.putImageData(out, 0, 0);
  return count;
}

// the line being sung, written in tiny letters (@ # * :) over the sky, with a thin dark rim around each stroke
const LY = new OffscreenCanvas(W, ART_H), ly = LY.getContext('2d', { willReadFrequently: true });
const SMALL = atlasSmall("@#*:");
function atlasSmall(chars) {
  const c = new OffscreenCanvas(4, 6), x = c.getContext('2d', { willReadFrequently: true });
  return Array.from(chars, ch => {
    x.fillStyle = '#000'; x.fillRect(0, 0, 4, 6); x.fillStyle = '#fff'; x.font = 'bold 7px Menlo, monospace';
    x.textAlign = 'center'; x.textBaseline = 'middle'; x.fillText(ch, 2, 3.3);
    const d = x.getImageData(0, 0, 4, 6).data, g = new Float32Array(24);
    for (let i = 0; i < 24; i++) g[i] = d[i * 4] / 255;
    return g;
  });
}
function lyric(t) {
  const L = LYRICS.find(([a, b]) => t >= a && t < b);
  if (!L) return;
  const [a, b, text, col] = L, alpha = 1;                                    // like the video: the whole line is just there, then gone
  const boil = Math.floor(t * FPS / 3);                                      // hand-drawn shimmer: redrawn every 3 frames, a pixel or two off
  const jx = Math.sin(boil * 12.9898) * 2, jy = Math.cos(boil * 78.233) * 1.5, jr = Math.sin(boil * 3.7) * 0.006;
  ly.fillStyle = '#000'; ly.fillRect(0, 0, W, ART_H);
  ly.font = '76px "Chalkboard SE", "Comic Sans MS", cursive'; ly.textAlign = 'center'; ly.textBaseline = 'top';
  let lines = [text];
  if (ly.measureText(text).width > W - 60) {
    const w = text.split(' '); let cut = 1, bd = 1e9;
    for (let k = 1; k < w.length; k++) { const dd = Math.abs(ly.measureText(w.slice(0, k).join(' ')).width - ly.measureText(w.slice(k).join(' ')).width); if (dd < bd) { bd = dd; cut = k; } }
    lines = [w.slice(0, cut).join(' '), w.slice(cut).join(' ')];
  }
  let y = lines.length === 1 ? 160 : 116;                                     // just above the riders' heads, as in the video
  ly.fillStyle = '#fff'; ly.strokeStyle = '#fff'; ly.lineWidth = 3;          // a little bolder so strokes survive the tiny cells
  ly.save(); ly.translate(W / 2 + jx, jy); ly.rotate(jr);
  for (const ln of lines) { ly.strokeText(ln, 0, y); ly.fillText(ln, 0, y); y += 88; }
  ly.restore();
  const m = ly.getImageData(0, 0, W, 330).data, img = ctx.getImageData(0, 0, W, 330), d = img.data;
  const at_ = (x, y) => (x < 0 || y < 0 || x >= W || y >= 330) ? 0 : m[(y * W + x) * 4] / 255 * alpha;
  for (let r = 0; r < 330 / CH | 0; r++) for (let c = 0; c < COLS; c++) {   // big letter cells under the strokes are emptied first
    let s = 0;
    for (let y = 0; y < CH; y++) for (let x = 0; x < CW; x++) s += at_(c * CW + x, r * CH + y);
    if (s / 96 > 0.06) for (let y = 0; y < CH; y++) for (let x = 0; x < CW; x++) { const o = ((r * CH + y) * W + c * CW + x) * 4; d[o] = BG[0]; d[o + 1] = BG[1]; d[o + 2] = BG[2]; }
  }
  for (let y = 0; y < 330; y++) for (let x = 0; x < W; x++) {               // rim: 2px around the stroke, darkened
    if (at_(x, y) > 0.3) continue;
    let near = false;
    for (let dy = -2; dy <= 2 && !near; dy++) for (let dx = -2; dx <= 2; dx++) if (dx * dx + dy * dy <= 5 && at_(x + dx, y + dy) > 0.3) { near = true; break; }
    if (near) { const o = (y * W + x) * 4; d[o] = lerp(d[o], BG[0], alpha); d[o + 1] = lerp(d[o + 1], BG[1], alpha); d[o + 2] = lerp(d[o + 2], BG[2], alpha); }
  }
  for (let r = 0; r < 330 / 6; r++) for (let c = 0; c < W / 4; c++) {        // 4x6 cells: dense stroke -> @, thinner -> # or *
    let s = 0;
    for (let y = 0; y < 6; y++) for (let x = 0; x < 4; x++) s += at_(c * 4 + x, r * 6 + y);
    const T = s / 24;
    if (T <= 0.25) continue;
    const g = SMALL[T > 0.55 ? 0 : T > 0.35 ? 1 : 2];
    for (let y = 0; y < 6; y++) for (let x = 0; x < 4; x++) {
      const v = g[y * 4 + x], o = ((r * 6 + y) * W + c * 4 + x) * 4;
      d[o] = lerp(d[o], col[0], v); d[o + 1] = lerp(d[o + 1], col[1], v); d[o + 2] = lerp(d[o + 2], col[2], v);
    }
  }
  ctx.putImageData(img, 0, 0);
}

// ---- the editor below: this file scrolling at four lines a second ----
const KW = new Set('const let function return for if else new of in await async true false null Math'.split(' '));
function tokens(line) {
  const re = /(\/\/.*$)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)|(\b\d+(?:\.\d+)?\b)|([A-Za-z_]\w*)/g;
  const parts = []; let last = 0, m;
  while ((m = re.exec(line))) {
    if (m.index > last) parts.push([line.slice(last, m.index), '#c8ccd4']);
    parts.push([m[0], m[1] ? '#5c6370' : m[2] ? '#c3e88d' : m[3] ? '#f78c6c' : KW.has(m[4]) ? '#c792ea' : line[re.lastIndex] === '(' ? '#82aaff' : '#c8ccd4']);
    last = re.lastIndex;
  }
  if (last < line.length) parts.push([line.slice(last), '#c8ccd4']);
  return parts;
}
const CODE = SOURCE.map(tokens);
function editor(t, n, count) {
  ctx.fillStyle = '#000'; ctx.fillRect(0, ART_H, W, H - ART_H);
  ctx.textBaseline = 'alphabetic'; ctx.textAlign = 'left'; ctx.font = '17px Menlo, monospace'; ctx.fillStyle = '#80858f';
  ctx.fillText(`time ${t.toFixed(1).padStart(5, '0')}s   frame ${String(n).padStart(4, '0')}   letters ${count.toLocaleString()}   @ai.asap.kr`, 24, 1279);
  ctx.textAlign = 'right'; ctx.font = '13px Menlo, monospace'; ctx.fillStyle = '#5d626b'; ctx.fillText('music: HONNE - B I K E', W - 20, 1279);
  ctx.fillStyle = '#2b2e35'; ctx.fillRect(0, CODE_TOP, W, 1);
  ctx.textBaseline = 'middle'; ctx.font = '21px Menlo, monospace';
  ctx.textAlign = 'left'; ctx.fillStyle = '#c8ccd4'; ctx.fillText('bike_ascii.js', 28, CODE_TOP + 34);
  ctx.textAlign = 'right'; ctx.fillStyle = '#8b9099'; ctx.fillText('running · 25 fps', W - 28, CODE_TOP + 34);
  ctx.fillStyle = '#ff9a3c'; ctx.fillText('●', W - 222, CODE_TOP + 34);
  const pos = CODE_ROWS + t * 4, newest = Math.floor(pos), k = Math.min(1, (pos - newest) / 0.45);
  const slide = 1 - (k < 0.5 ? 2 * k * k : 1 - (2 - 2 * k) ** 2 / 2), top = CODE_TOP + 64;
  ctx.font = '23px Menlo, monospace'; const cw = ctx.measureText('M').width;
  for (let r = -1; r < CODE_ROWS; r++) {
    const ln = newest - CODE_ROWS + 1 + r, y = top + 4 + (r + slide) * LINE_H, mid = y + LINE_H / 2;
    if (mid < top + 6 || y > H) continue;
    const idx = ((ln % CODE.length) + CODE.length) % CODE.length;
    if (ln === newest) { const a = 23 * (1 - (pos - newest) * 0.5) | 0; ctx.fillStyle = `rgb(${a},${a},${a})`; ctx.fillRect(0, y, W, LINE_H); }
    ctx.textAlign = 'right'; ctx.fillStyle = '#555a63'; ctx.fillText(String(idx + 1), 74, mid);
    ctx.textAlign = 'left'; let x = 96;
    for (const [s, c] of CODE[idx]) { ctx.fillStyle = c; ctx.fillText(s, x, mid); x += s.length * cw; if (x > W) break; }
  }
}

// ---- run: 25 frames a second, 90 seconds, then again ----
window.bikeAscii = { paint, letters, lyric, editor, frameCanvas: F };
let frozen = false;
window.render = t => { frozen = true; const n = Math.round(t * FPS); paint(t); const c = letters(); lyric(t); editor(t, n, c); };   // record one exact frame (stops the clock)                       // handy in the console: bikeAscii.paint(30)
document.getElementById('go').remove();
const t0 = performance.now();
let last = -1;
function tick(now) {
  const n = Math.floor((now - t0) / 1000 * FPS) % (DUR * FPS);
  if (!frozen && n !== last) { last = n; const t = n / FPS; paint(t); const count = letters(); lyric(t); editor(t, n, count); }
  requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
})();
</script>
</body>
</html>
광고