Living fishtank: draw fish, release them, feed them (Advent of AI Slop day 1)
This commit is contained in:
commit
ecd1e99139
14 files changed
+1445
No files matched your search
@@ -0,0 +1,39 @@
|
||||
// <advent-badge day="1">: the link in the top right corner, back to the door of the day this was made for.
|
||||
// It draws itself in a shadow root, so its styles and the page's never touch.
|
||||
const site = 'https://advent-of-slop.quesma.com';
|
||||
|
||||
const css = `
|
||||
a {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
z-index: 2147483647;
|
||||
padding: 0.35rem 0.7rem;
|
||||
border-bottom-left-radius: 0.5rem;
|
||||
background: #b8232f;
|
||||
color: #f6ecd6;
|
||||
font: 700 0.8125rem/1.2 system-ui, sans-serif;
|
||||
text-decoration: none;
|
||||
}
|
||||
a:hover {
|
||||
background: #0f3b2d;
|
||||
}
|
||||
`;
|
||||
|
||||
class AdventBadge extends HTMLElement {
|
||||
connectedCallback(): void {
|
||||
const day = Number(this.getAttribute('day'));
|
||||
if (!Number.isInteger(day) || day < 1 || day > 24) {
|
||||
throw new Error(`<advent-badge> needs day="1" to day="24", got ${this.getAttribute('day')}`);
|
||||
}
|
||||
const style = document.createElement('style');
|
||||
style.textContent = css;
|
||||
const link = document.createElement('a');
|
||||
link.href = `${site}/day/${day}/`;
|
||||
link.textContent = 'Advent of AI Slop';
|
||||
link.title = `Made for day ${day} of Advent of AI Slop`;
|
||||
this.attachShadow({ mode: 'open' }).append(style, link);
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('advent-badge', AdventBadge);
|
||||
+533
@@ -0,0 +1,533 @@
|
||||
// Living fishtank — Advent of AI Slop, day 1.
|
||||
// Draw a fish in the studio, release it, and it swims. Click the water to feed them.
|
||||
|
||||
const app = document.querySelector<HTMLElement>('#app');
|
||||
if (app === null) throw new Error('Missing #app in index.html');
|
||||
|
||||
app.innerHTML = `
|
||||
<div class="tank-wrap">
|
||||
<canvas id="tank"></canvas>
|
||||
<div class="hud">
|
||||
<span id="count">0 fish</span>
|
||||
<button id="feed" type="button">Feed the fish</button>
|
||||
</div>
|
||||
<p id="hint" class="hint" hidden>Draw a fish on the right, then press <b>Release into the tank</b> — or click the water to drop food.</p>
|
||||
</div>
|
||||
<aside id="panel" class="panel open">
|
||||
<button id="toggle" class="toggle" type="button" title="Show or hide the studio">🎨 Fish studio</button>
|
||||
<div class="panel-body">
|
||||
<canvas id="studio" width="320" height="220"></canvas>
|
||||
<div class="row swatches" id="swatches"></div>
|
||||
<div class="row tools">
|
||||
<label class="size">Brush <input id="brush" type="range" min="3" max="40" value="14"></label>
|
||||
<button id="eraser" type="button" title="Erase">⌫</button>
|
||||
<button id="undo" type="button" title="Undo">↩︎</button>
|
||||
<button id="clear" type="button" title="Clear">🗑</button>
|
||||
</div>
|
||||
<div class="row actions">
|
||||
<button id="release" class="primary" type="button">Release into the tank</button>
|
||||
<button id="random" type="button" title="Generate a random fish">🎲 Random fish</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
`;
|
||||
|
||||
const style = document.createElement('style');
|
||||
style.textContent = `
|
||||
:root { color-scheme: dark; }
|
||||
html, body { margin: 0; height: 100%; overflow: hidden; background: #06222e;
|
||||
font: 15px/1.4 system-ui, sans-serif; color: #e8f4f2; }
|
||||
#app { height: 100%; position: relative; }
|
||||
.tank-wrap { position: absolute; inset: 0; }
|
||||
#tank { width: 100%; height: 100%; display: block; cursor: crosshair; }
|
||||
.hud { position: absolute; left: 14px; bottom: 12px; display: flex; gap: 10px; align-items: center; }
|
||||
.hud span { font-size: .85rem; opacity: .75; }
|
||||
.hint { position: absolute; left: 50%; bottom: 18px; transform: translateX(-50%);
|
||||
margin: 0; padding: .5rem .9rem; border-radius: .6rem; background: rgba(4,20,28,.72);
|
||||
backdrop-filter: blur(6px); font-size: .9rem; }
|
||||
button { font: inherit; border: 1px solid rgba(255,255,255,.18); border-radius: .55rem;
|
||||
background: rgba(9,42,56,.8); color: #e8f4f2; padding: .35rem .8rem; cursor: pointer; }
|
||||
button:hover { background: rgba(16,64,84,.9); }
|
||||
button.primary { background: #b8232f; border-color: #d45660; font-weight: 700; }
|
||||
button.primary:hover { background: #d0303e; }
|
||||
button.primary:disabled { opacity: .45; cursor: default; }
|
||||
button.on { background: #0f3b2d; border-color: #3f8f74; }
|
||||
.panel { position: absolute; top: 0; right: 0; height: 100%; z-index: 5;
|
||||
transform: translateX(calc(100% - 2.6rem)); transition: transform .25s ease; }
|
||||
.panel.open { transform: translateX(0); }
|
||||
.toggle { position: absolute; left: -2.6rem; top: 50%; transform: translateY(-50%);
|
||||
writing-mode: vertical-rl; border-radius: .55rem 0 0 .55rem; padding: .7rem .45rem; z-index: 6; }
|
||||
.panel.open .toggle { writing-mode: horizontal-tb; left: -3.4rem; right: auto; top: 12px;
|
||||
transform: none; border-radius: .55rem 0 0 .55rem; }
|
||||
.panel-body { height: 100%; box-sizing: border-box; padding: 52px 14px 14px;
|
||||
width: 348px; background: rgba(6,28,38,.88); backdrop-filter: blur(10px);
|
||||
border-left: 1px solid rgba(255,255,255,.12); display: flex; flex-direction: column; gap: 10px; }
|
||||
#studio { width: 100%; aspect-ratio: 320/220; border-radius: .6rem; touch-action: none;
|
||||
background: #dcece6; border: 1px solid rgba(255,255,255,.2); cursor: crosshair; }
|
||||
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
|
||||
.swatches button { width: 26px; height: 26px; padding: 0; border-radius: 50%; }
|
||||
.swatches button.sel { outline: 2px solid #fff; }
|
||||
.size { display: flex; gap: 6px; align-items: center; font-size: .85rem; flex: 1; }
|
||||
.size input { flex: 1; accent-color: #b8232f; }
|
||||
@media (max-width: 720px) { .panel-body { width: min(348px, 92vw); } }
|
||||
`;
|
||||
document.head.append(style);
|
||||
|
||||
// ---------- tank ----------
|
||||
interface FishSpec { src: string; scale: number }
|
||||
interface Fish {
|
||||
img: HTMLImageElement; x: number; y: number; vx: number; vy: number;
|
||||
facing: 1 | -1; speed: number; scale: number; phase: number;
|
||||
tx: number; ty: number; retarget: number; depth: number;
|
||||
}
|
||||
interface Pellet { x: number; y: number; vy: number; vx: number }
|
||||
interface Bubble { x: number; y: number; r: number; vy: number; wob: number }
|
||||
|
||||
const tankCanvas = document.getElementById('tank') as HTMLCanvasElement;
|
||||
const tctx = tankCanvas.getContext('2d')!;
|
||||
const countEl = document.getElementById('count')!;
|
||||
const hintEl = document.getElementById('hint')!;
|
||||
|
||||
let W = 0, H = 0, DPR = 1;
|
||||
function resize(): void {
|
||||
DPR = Math.min(window.devicePixelRatio || 1, 2);
|
||||
W = tankCanvas.clientWidth; H = tankCanvas.clientHeight;
|
||||
tankCanvas.width = Math.round(W * DPR); tankCanvas.height = Math.round(H * DPR);
|
||||
tctx.setTransform(DPR, 0, 0, DPR, 0, 0);
|
||||
}
|
||||
window.addEventListener('resize', resize);
|
||||
resize();
|
||||
|
||||
const fish: Fish[] = [];
|
||||
const pellets: Pellet[] = [];
|
||||
const bubbles: Bubble[] = [];
|
||||
|
||||
const sandTop = (): number => H - Math.max(46, H * 0.09);
|
||||
|
||||
// scenery, generated once per size
|
||||
let plants: { x: number; h: number; hue: number; sway: number }[] = [];
|
||||
let pebbles: { x: number; y: number; r: number; g: number }[] = [];
|
||||
function genScenery(): void {
|
||||
plants = []; pebbles = [];
|
||||
const n = Math.max(4, Math.round(W / 220));
|
||||
for (let i = 0; i < n; i++) {
|
||||
plants.push({
|
||||
x: 30 + Math.random() * (W - 60), h: 60 + Math.random() * 160,
|
||||
hue: 95 + Math.random() * 60, sway: 0.5 + Math.random(),
|
||||
});
|
||||
}
|
||||
for (let i = 0; i < 26; i++) {
|
||||
pebbles.push({
|
||||
x: Math.random() * W, y: sandTop() + 8 + Math.random() * (H - sandTop() - 14),
|
||||
r: 2 + Math.random() * 5, g: 90 + Math.random() * 60,
|
||||
});
|
||||
}
|
||||
}
|
||||
genScenery();
|
||||
window.addEventListener('resize', genScenery);
|
||||
|
||||
// ---------- fish behaviour ----------
|
||||
function addFish(spec: FishSpec, img: HTMLImageElement): void {
|
||||
const depth = 0.55 + Math.random() * 0.45; // 0.55 back .. 1 front
|
||||
const scale = spec.scale * (0.75 + depth * 0.45);
|
||||
const y = 60 + Math.random() * Math.max(60, sandTop() - 120);
|
||||
const f: Fish = {
|
||||
img, x: Math.random() * W, y, vx: 0, vy: 0,
|
||||
facing: Math.random() < 0.5 ? 1 : -1,
|
||||
speed: (26 + Math.random() * 40) * (1.15 - depth * 0.35),
|
||||
scale, phase: Math.random() * Math.PI * 2,
|
||||
tx: Math.random() * W, ty: y, retarget: 0, depth,
|
||||
};
|
||||
fish.push(f);
|
||||
save();
|
||||
updateHud();
|
||||
}
|
||||
|
||||
function steer(f: Fish, dt: number, t: number): void {
|
||||
f.retarget -= dt;
|
||||
let gx = f.tx, gy = f.ty;
|
||||
// food wins
|
||||
let best: Pellet | null = null, bd = 1e9;
|
||||
for (const p of pellets) {
|
||||
const d = Math.hypot(p.x - f.x, p.y - f.y);
|
||||
if (d < bd) { bd = d; best = p; }
|
||||
}
|
||||
if (best !== null && bd < Math.min(W, H) * 0.6) { gx = best.x; gy = best.y; }
|
||||
else if (f.retarget <= 0) {
|
||||
f.retarget = 3 + Math.random() * 5;
|
||||
f.tx = 40 + Math.random() * Math.max(60, W - 80);
|
||||
f.ty = 50 + Math.random() * Math.max(60, sandTop() - 110);
|
||||
}
|
||||
const dx = gx - f.x, dy = gy - f.y;
|
||||
const d = Math.hypot(dx, dy) || 1;
|
||||
const ax = (dx / d) * f.speed, ay = (dy / d) * f.speed * 0.6;
|
||||
f.vx += (ax - f.vx) * Math.min(1, dt * 1.4);
|
||||
f.vy += (ay - f.vy + Math.sin(t * 1.7 + f.phase) * 6) * Math.min(1, dt * 1.4);
|
||||
if (Math.abs(f.vx) > 4) f.facing = f.vx > 0 ? 1 : -1;
|
||||
f.x += f.vx * dt; f.y += f.vy * dt;
|
||||
f.x = Math.max(20, Math.min(W - 20, f.x));
|
||||
f.y = Math.max(30, Math.min(sandTop() - 14, f.y));
|
||||
// eat pellets
|
||||
for (let i = pellets.length - 1; i >= 0; i--) {
|
||||
const p = pellets[i]!;
|
||||
if (Math.hypot(p.x - f.x, p.y - f.y) < 26 * f.scale + 6) {
|
||||
pellets.splice(i, 1);
|
||||
for (let b = 0; b < 3; b++)
|
||||
bubbles.push({ x: p.x, y: p.y, r: 1.5 + Math.random() * 2, vy: 40 + Math.random() * 30, wob: Math.random() * 6 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawFish(f: Fish, t: number): void {
|
||||
const img = f.img;
|
||||
const w = img.naturalWidth * f.scale, h = img.naturalHeight * f.scale;
|
||||
const strips = 14;
|
||||
const sw = img.naturalWidth / strips;
|
||||
const speedNorm = Math.min(1, Math.hypot(f.vx, f.vy) / f.speed);
|
||||
const wig = 0.10 + 0.16 * speedNorm; // tail swing amplitude (fraction of height)
|
||||
const ang = Math.atan2(f.vy, Math.abs(f.vx) + 1) * 0.55;
|
||||
tctx.save();
|
||||
tctx.translate(f.x, f.y);
|
||||
tctx.rotate(f.facing === 1 ? ang : -ang);
|
||||
tctx.scale(f.facing, 1);
|
||||
tctx.globalAlpha = 0.55 + f.depth * 0.45;
|
||||
const squash = 1 + 0.02 * Math.sin(t * 6 + f.phase);
|
||||
tctx.scale(squash, 1);
|
||||
for (let i = 0; i < strips; i++) {
|
||||
const s = i / (strips - 1); // 0 head .. 1 tail
|
||||
const off = Math.sin(t * 7 + f.phase - i * 0.55) * wig * h * s * s;
|
||||
tctx.drawImage(img, i * sw, 0, sw + 0.6, img.naturalHeight,
|
||||
-w / 2 + i * (w / strips), off - h / 2, w / strips + 0.6, h);
|
||||
}
|
||||
tctx.restore();
|
||||
}
|
||||
|
||||
// ---------- background ----------
|
||||
function drawScene(t: number): void {
|
||||
const g = tctx.createLinearGradient(0, 0, 0, H);
|
||||
g.addColorStop(0, '#0d4f66'); g.addColorStop(0.55, '#0a3a4e'); g.addColorStop(1, '#06222e');
|
||||
tctx.fillStyle = g; tctx.fillRect(0, 0, W, H);
|
||||
|
||||
// caustics
|
||||
tctx.save();
|
||||
tctx.globalCompositeOperation = 'soft-light';
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const cx = (W * (0.1 + 0.2 * i) + Math.sin(t * 0.3 + i * 2.1) * W * 0.12);
|
||||
const cy = H * 0.25 + Math.cos(t * 0.23 + i * 1.7) * H * 0.15;
|
||||
const r = Math.min(W, H) * (0.25 + 0.1 * Math.sin(t * 0.4 + i));
|
||||
const rg = tctx.createRadialGradient(cx, cy, 0, cx, cy, r);
|
||||
rg.addColorStop(0, 'rgba(190,255,240,0.5)'); rg.addColorStop(1, 'rgba(190,255,240,0)');
|
||||
tctx.fillStyle = rg; tctx.fillRect(0, 0, W, H);
|
||||
}
|
||||
tctx.restore();
|
||||
|
||||
// plants behind sand
|
||||
const st = sandTop();
|
||||
for (const p of plants) {
|
||||
tctx.strokeStyle = `hsl(${p.hue} 45% 30%)`;
|
||||
tctx.lineCap = 'round';
|
||||
for (let s = 0; s < 3; s++) {
|
||||
tctx.lineWidth = 7 - s * 2;
|
||||
const sway = Math.sin(t * p.sway + s * 1.3) * 14;
|
||||
tctx.beginPath();
|
||||
tctx.moveTo(p.x + s * 6, st + 6);
|
||||
tctx.quadraticCurveTo(p.x + s * 6 + sway * 0.5, st - p.h * 0.6, p.x + s * 6 + sway, st - p.h * (0.7 + s * 0.12));
|
||||
tctx.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
// sand
|
||||
tctx.fillStyle = '#c9b283';
|
||||
tctx.beginPath();
|
||||
tctx.moveTo(0, H); tctx.lineTo(0, st + 6);
|
||||
for (let x = 0; x <= W; x += 40)
|
||||
tctx.lineTo(x, st + 6 + Math.sin(x * 0.02 + 2) * 5);
|
||||
tctx.lineTo(W, H); tctx.closePath(); tctx.fill();
|
||||
for (const p of pebbles) {
|
||||
tctx.fillStyle = `rgb(${p.g + 40},${p.g + 30},${p.g + 20})`;
|
||||
tctx.beginPath(); tctx.ellipse(p.x, p.y, p.r, p.r * 0.7, 0, 0, Math.PI * 2); tctx.fill();
|
||||
}
|
||||
}
|
||||
|
||||
function drawBubbles(dt: number): void {
|
||||
if (Math.random() < dt * 1.2) {
|
||||
bubbles.push({ x: 30 + Math.random() * (W - 60), y: sandTop(), r: 2 + Math.random() * 4, vy: 35 + Math.random() * 35, wob: Math.random() * 6 });
|
||||
}
|
||||
tctx.strokeStyle = 'rgba(220,250,255,0.5)';
|
||||
tctx.lineWidth = 1.2;
|
||||
for (let i = bubbles.length - 1; i >= 0; i--) {
|
||||
const b = bubbles[i]!;
|
||||
b.y -= b.vy * dt; b.x += Math.sin(b.y * 0.05 + b.wob) * 12 * dt;
|
||||
if (b.y < 8) { bubbles.splice(i, 1); continue; }
|
||||
tctx.beginPath(); tctx.arc(b.x, b.y, b.r, 0, Math.PI * 2); tctx.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
function drawPellets(dt: number): void {
|
||||
tctx.fillStyle = '#8a5a2b';
|
||||
for (const p of pellets) {
|
||||
p.vy = Math.min(60, p.vy + 60 * dt);
|
||||
p.y += p.vy * dt; p.x += p.vx * dt; p.vx *= 1 - dt;
|
||||
if (p.y > sandTop() + 2) { p.y = sandTop() + 2; p.vy = 0; }
|
||||
tctx.beginPath(); tctx.arc(p.x, p.y, 3, 0, Math.PI * 2); tctx.fill();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- main loop ----------
|
||||
let last = performance.now();
|
||||
function frame(now: number): void {
|
||||
const dt = Math.min(0.05, (now - last) / 1000);
|
||||
const t = now / 1000;
|
||||
last = now;
|
||||
drawScene(t);
|
||||
drawPellets(dt);
|
||||
const sorted = [...fish].sort((a, b) => a.depth - b.depth);
|
||||
for (const f of sorted) { steer(f, dt, t); drawFish(f, t); }
|
||||
drawBubbles(dt);
|
||||
requestAnimationFrame(frame);
|
||||
}
|
||||
requestAnimationFrame(frame);
|
||||
|
||||
// ---------- feeding ----------
|
||||
document.getElementById('feed')!.addEventListener('click', () => dropFood(W / 2, 40));
|
||||
tankCanvas.addEventListener('pointerdown', (e) => {
|
||||
const r = tankCanvas.getBoundingClientRect();
|
||||
dropFood(e.clientX - r.left, e.clientY - r.top);
|
||||
});
|
||||
function dropFood(x: number, y: number): void {
|
||||
for (let i = 0; i < 7; i++)
|
||||
pellets.push({ x: x + (Math.random() - 0.5) * 46, y: y - Math.random() * 20, vy: 10 + Math.random() * 20, vx: (Math.random() - 0.5) * 20 });
|
||||
}
|
||||
|
||||
function updateHud(): void {
|
||||
countEl.textContent = `${fish.length} ${fish.length === 1 ? 'fish' : 'fish'}`;
|
||||
hintEl.hidden = fish.length > 0;
|
||||
}
|
||||
|
||||
// ---------- persistence ----------
|
||||
const LS = 'aos-01-living-fishtank';
|
||||
function save(): void {
|
||||
try {
|
||||
localStorage.setItem(LS, JSON.stringify(specs));
|
||||
} catch { /* private mode etc. */ }
|
||||
}
|
||||
let specs: FishSpec[] = [];
|
||||
function loadSaved(): void {
|
||||
try {
|
||||
const raw = localStorage.getItem(LS);
|
||||
if (!raw) return;
|
||||
specs = JSON.parse(raw) as FishSpec[];
|
||||
} catch { specs = []; }
|
||||
for (const s of specs.slice(0, 40)) {
|
||||
const img = new Image();
|
||||
img.onload = () => addFish(s, img);
|
||||
img.src = s.src;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- studio ----------
|
||||
const panel = document.getElementById('panel')!;
|
||||
document.getElementById('toggle')!.addEventListener('click', () => panel.classList.toggle('open'));
|
||||
|
||||
const studio = document.getElementById('studio') as HTMLCanvasElement;
|
||||
const sctx = studio.getContext('2d', { willReadFrequently: true })!;
|
||||
const releaseBtn = document.getElementById('release') as HTMLButtonElement;
|
||||
|
||||
const COLORS: string[] = ['#e4572e', '#f3a712', '#d6409f', '#2e86ab', '#3aa76d', '#f6f7fb', '#2b2d42', '#8d5524'];
|
||||
const swatchRow = document.getElementById('swatches')!;
|
||||
let color: string = COLORS[0] ?? '#e4572e';
|
||||
let erasing = false;
|
||||
let brush = 14;
|
||||
COLORS.forEach((c, i) => {
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button'; b.style.background = c; b.title = c;
|
||||
if (i === 0) b.classList.add('sel');
|
||||
b.addEventListener('click', () => {
|
||||
color = c; erasing = false;
|
||||
swatchRow.querySelector('.sel')?.classList.remove('sel');
|
||||
b.classList.add('sel');
|
||||
document.getElementById('eraser')!.classList.remove('on');
|
||||
});
|
||||
swatchRow.append(b);
|
||||
});
|
||||
document.getElementById('brush')!.addEventListener('input', (e) => {
|
||||
brush = Number((e.target as HTMLInputElement).value);
|
||||
});
|
||||
const eraserBtn = document.getElementById('eraser')!;
|
||||
eraserBtn.addEventListener('click', () => {
|
||||
erasing = !erasing;
|
||||
eraserBtn.classList.toggle('on', erasing);
|
||||
});
|
||||
|
||||
// undo snapshots
|
||||
const undoStack: ImageData[] = [];
|
||||
document.getElementById('undo')!.addEventListener('click', () => {
|
||||
const s = undoStack.pop();
|
||||
if (s) { sctx.clearRect(0, 0, studio.width, studio.height); sctx.putImageData(s, 0, 0); checkEmpty(); }
|
||||
});
|
||||
document.getElementById('clear')!.addEventListener('click', () => {
|
||||
pushUndo(); sctx.clearRect(0, 0, studio.width, studio.height); checkEmpty();
|
||||
});
|
||||
function pushUndo(): void {
|
||||
undoStack.push(sctx.getImageData(0, 0, studio.width, studio.height));
|
||||
if (undoStack.length > 15) undoStack.shift();
|
||||
}
|
||||
|
||||
let drawing = false, lx = 0, ly = 0;
|
||||
function pos(e: PointerEvent): [number, number] {
|
||||
const r = studio.getBoundingClientRect();
|
||||
return [(e.clientX - r.left) * (studio.width / r.width), (e.clientY - r.top) * (studio.height / r.height)];
|
||||
}
|
||||
studio.addEventListener('pointerdown', (e) => {
|
||||
e.preventDefault();
|
||||
studio.setPointerCapture(e.pointerId);
|
||||
pushUndo();
|
||||
drawing = true; [lx, ly] = pos(e);
|
||||
dot(lx, ly);
|
||||
});
|
||||
studio.addEventListener('pointermove', (e) => {
|
||||
if (!drawing) return;
|
||||
const [x, y] = pos(e);
|
||||
sctx.save();
|
||||
sctx.lineCap = 'round'; sctx.lineJoin = 'round'; sctx.lineWidth = brush;
|
||||
sctx.globalCompositeOperation = erasing ? 'destination-out' : 'source-over';
|
||||
sctx.strokeStyle = color;
|
||||
sctx.beginPath(); sctx.moveTo(lx, ly); sctx.lineTo(x, y); sctx.stroke();
|
||||
sctx.restore();
|
||||
[lx, ly] = [x, y];
|
||||
checkEmpty();
|
||||
});
|
||||
studio.addEventListener('pointerup', () => { drawing = false; checkEmpty(); });
|
||||
function dot(x: number, y: number): void {
|
||||
sctx.save();
|
||||
sctx.globalCompositeOperation = erasing ? 'destination-out' : 'source-over';
|
||||
sctx.fillStyle = color;
|
||||
sctx.beginPath(); sctx.arc(x, y, brush / 2, 0, Math.PI * 2); sctx.fill();
|
||||
sctx.restore();
|
||||
}
|
||||
function checkEmpty(): void {
|
||||
releaseBtn.disabled = !hasInk();
|
||||
}
|
||||
function hasInk(): boolean {
|
||||
const d = sctx.getImageData(0, 0, studio.width, studio.height).data;
|
||||
for (let i = 3; i < d.length; i += 4) if (d[i]! > 0) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------- release pipeline ----------
|
||||
function releaseCurrent(): void {
|
||||
if (!hasInk()) return;
|
||||
const src = studio.toDataURL('image/png');
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
const trimmed = trimImage(img);
|
||||
const scale = Math.min(1.1, Math.max(0.35, trimmed.h / 150));
|
||||
const spec: FishSpec = { src: trimmed.src, scale };
|
||||
specs.push(spec);
|
||||
if (specs.length > 40) specs.shift();
|
||||
addFish(spec, trimmed.img);
|
||||
};
|
||||
img.src = src;
|
||||
}
|
||||
|
||||
interface Trimmed { src: string; h: number; img: HTMLImageElement }
|
||||
function trimImage(img: HTMLImageElement): Trimmed {
|
||||
const c = document.createElement('canvas');
|
||||
c.width = img.naturalWidth; c.height = img.naturalHeight;
|
||||
const ctx = c.getContext('2d', { willReadFrequently: true })!;
|
||||
ctx.drawImage(img, 0, 0);
|
||||
const { data } = ctx.getImageData(0, 0, c.width, c.height);
|
||||
let minX = c.width, minY = c.height, maxX = 0, maxY = 0;
|
||||
for (let y = 0; y < c.height; y++) {
|
||||
for (let x = 0; x < c.width; x++) {
|
||||
if (data[(y * c.width + x) * 4 + 3]! > 10) {
|
||||
if (x < minX) minX = x; if (x > maxX) maxX = x;
|
||||
if (y < minY) minY = y; if (y > maxY) maxY = y;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (maxX < minX) { minX = 0; minY = 0; maxX = c.width - 1; maxY = c.height - 1; }
|
||||
const pad = 2;
|
||||
minX = Math.max(0, minX - pad); minY = Math.max(0, minY - pad);
|
||||
maxX = Math.min(c.width - 1, maxX + pad); maxY = Math.min(c.height - 1, maxY + pad);
|
||||
const w = maxX - minX + 1, h = maxY - minY + 1;
|
||||
const out = document.createElement('canvas');
|
||||
out.width = w; out.height = h;
|
||||
const octx = out.getContext('2d')!;
|
||||
octx.drawImage(c, minX, minY, w, h, 0, 0, w, h);
|
||||
// orient: fish heads taper, tails flare — flip so the narrower end faces right
|
||||
const od = octx.getImageData(0, 0, w, h).data;
|
||||
const colH = (x0: number, x1: number): number => {
|
||||
let sum = 0;
|
||||
for (let x = x0; x < x1; x++) {
|
||||
let top = -1, bot = -1;
|
||||
for (let y = 0; y < h; y++) {
|
||||
const a = od[(y * w + x) * 4 + 3]!;
|
||||
if (a > 10) { if (top < 0) top = y; bot = y; }
|
||||
}
|
||||
sum += top < 0 ? 0 : bot - top;
|
||||
}
|
||||
return sum / Math.max(1, x1 - x0);
|
||||
};
|
||||
const band = Math.max(3, Math.round(w * 0.2));
|
||||
const leftH = colH(0, band), rightH = colH(w - band, w);
|
||||
const flipped = document.createElement('canvas');
|
||||
flipped.width = w; flipped.height = h;
|
||||
const fctx = flipped.getContext('2d')!;
|
||||
if (leftH < rightH) { // head already on the right
|
||||
fctx.drawImage(out, 0, 0);
|
||||
} else { // mirror so head faces right
|
||||
fctx.translate(w, 0); fctx.scale(-1, 1); fctx.drawImage(out, 0, 0);
|
||||
}
|
||||
const src = flipped.toDataURL('image/png');
|
||||
const fimg = new Image(); fimg.src = src;
|
||||
return { src, h, img: fimg };
|
||||
}
|
||||
|
||||
releaseBtn.addEventListener('click', releaseCurrent);
|
||||
checkEmpty();
|
||||
|
||||
// ---------- random fish ----------
|
||||
document.getElementById('random')!.addEventListener('click', () => {
|
||||
const c = document.createElement('canvas');
|
||||
c.width = 200; c.height = 130;
|
||||
const ctx = c.getContext('2d')!;
|
||||
const hue = Math.floor(Math.random() * 360);
|
||||
const body = `hsl(${hue} 70% 55%)`, dark = `hsl(${hue} 70% 38%)`;
|
||||
// tail
|
||||
ctx.fillStyle = dark;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(58, 65); ctx.lineTo(14, 34); ctx.lineTo(24, 65); ctx.lineTo(14, 96); ctx.closePath(); ctx.fill();
|
||||
// body
|
||||
const g = ctx.createLinearGradient(0, 30, 0, 100);
|
||||
g.addColorStop(0, body); g.addColorStop(1, dark);
|
||||
ctx.fillStyle = g;
|
||||
ctx.beginPath(); ctx.ellipse(110, 65, 62, 34, 0, 0, Math.PI * 2); ctx.fill();
|
||||
// dorsal fin
|
||||
ctx.fillStyle = dark;
|
||||
ctx.beginPath(); ctx.moveTo(95, 34); ctx.quadraticCurveTo(115, 8, 135, 36); ctx.closePath(); ctx.fill();
|
||||
// stripes
|
||||
ctx.strokeStyle = `hsla(${(hue + 40) % 360} 80% 80% / .55)`;
|
||||
ctx.lineWidth = 7; ctx.lineCap = 'round';
|
||||
for (let i = 0; i < 3; i++) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(88 + i * 20, 40 + i * 2);
|
||||
ctx.quadraticCurveTo(84 + i * 20, 65, 88 + i * 20, 90 - i * 2);
|
||||
ctx.stroke();
|
||||
}
|
||||
// eye
|
||||
ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(150, 57, 8, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.fillStyle = '#151515'; ctx.beginPath(); ctx.arc(152, 57, 4, 0, Math.PI * 2); ctx.fill();
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
const trimmed = trimImage(img);
|
||||
const spec: FishSpec = { src: trimmed.src, scale: Math.min(1.1, Math.max(0.35, trimmed.h / 150)) };
|
||||
specs.push(spec);
|
||||
if (specs.length > 40) specs.shift();
|
||||
addFish(spec, trimmed.img);
|
||||
};
|
||||
img.src = c.toDataURL('image/png');
|
||||
});
|
||||
|
||||
loadSaved();
|
||||
updateHud();
|
||||
Reference in new issue
Block a user