// Pixel selections. A selection is an immutable alpha mask canvas (doc-sized); // operations always return a new Selection so history can keep references. import { createCanvas, cloneCanvas, opaqueBounds } from './util.js'; import { blurAlpha } from '../imaging/blur.js'; export class Selection { constructor(mask) { this.mask = mask; this._bounds = undefined; this._outline = null; } get width() { return this.mask.width; } get height() { return this.mask.height; } /** Bounding box of selected pixels, or null if nothing is selected. */ get bounds() { if (this._bounds === undefined) this._bounds = opaqueBounds(this.mask, 0); return this._bounds; } get isEmpty() { return !this.bounds; } /** Path2D of the boundary of the selection (alpha >= 128), in doc pixels. */ get outline() { if (this._outline) return this._outline; const { width: w, height: h } = this.mask; const path = new Path2D(); const b = this.bounds; if (!b) return (this._outline = path); const data = this.mask.getContext('2d', { willReadFrequently: true }).getImageData(0, 0, w, h).data; const inside = (x, y) => x >= 0 && y >= 0 && x < w && y < h && data[(y * w + x) * 4 + 3] >= 128; const x0 = Math.max(0, b.x - 1), x1 = Math.min(w, b.x + b.w + 1); const y0 = Math.max(0, b.y - 1), y1 = Math.min(h, b.y + b.h + 1); // Horizontal edges: between rows y-1 and y. for (let y = y0; y <= y1; y++) { let run = -1; for (let x = x0; x <= x1; x++) { const edge = x < x1 && inside(x, y) !== inside(x, y - 1); if (edge && run < 0) run = x; else if (!edge && run >= 0) { path.moveTo(run, y); path.lineTo(x, y); run = -1; } } } // Vertical edges: between columns x-1 and x. for (let x = x0; x <= x1; x++) { let run = -1; for (let y = y0; y <= y1; y++) { const edge = y < y1 && inside(x, y) !== inside(x - 1, y); if (edge && run < 0) run = y; else if (!edge && run >= 0) { path.moveTo(x, run); path.lineTo(x, y); run = -1; } } } this._outline = path; return path; } /** Alpha (0..255) at a doc pixel. */ alphaAt(x, y) { x = Math.floor(x); y = Math.floor(y); if (x < 0 || y < 0 || x >= this.width || y >= this.height) return 0; return this.mask.getContext('2d', { willReadFrequently: true }).getImageData(x, y, 1, 1).data[3]; } contains(x, y) { return this.alphaAt(x, y) >= 128; } translated(dx, dy) { const c = createCanvas(this.width, this.height); c.getContext('2d').drawImage(this.mask, Math.round(dx), Math.round(dy)); return Selection.orNull(c); } inverted() { const c = createCanvas(this.width, this.height); const ctx = c.getContext('2d'); ctx.fillStyle = '#000'; ctx.fillRect(0, 0, c.width, c.height); ctx.globalCompositeOperation = 'destination-out'; ctx.drawImage(this.mask, 0, 0); return Selection.orNull(c); } feathered(radius) { if (radius <= 0) return this; const c = cloneCanvas(this.mask); blurAlpha(c, radius); return Selection.orNull(c); } /** Grow (positive) or shrink (negative) by approximately `amount` pixels. */ resized(amount) { if (!amount) return this; const c = cloneCanvas(this.mask); const r = Math.abs(amount); blurAlpha(c, r); const ctx = c.getContext('2d'); const id = ctx.getImageData(0, 0, c.width, c.height); const d = id.data; // After a blur of radius r, an edge pixel at distance r has alpha ~ 0 (grow) / ~255 (shrink). const thr = amount > 0 ? 8 : 247; for (let i = 3; i < d.length; i += 4) d[i] = d[i] > thr ? 255 : 0; ctx.putImageData(id, 0, 0); return Selection.orNull(c); } /** A band `width` px wide centred on the selection edge, or null. */ border(width) { const outer = this.resized(Math.ceil(width / 2)) || this; const inner = this.resized(-Math.floor(width / 2) || -1); const c = cloneCanvas(outer.mask); if (inner) { const ctx = c.getContext('2d'); ctx.globalCompositeOperation = 'destination-out'; ctx.drawImage(inner.mask, 0, 0); } return Selection.orNull(c); } /** Round off corners and drop specks smaller than about `radius` px. */ smoothed(radius) { if (radius <= 0) return this; const c = cloneCanvas(this.mask); blurAlpha(c, radius); const ctx = c.getContext('2d'); const id = ctx.getImageData(0, 0, c.width, c.height); const d = id.data; // a soft ramp keeps the new edge anti-aliased for (let i = 3; i < d.length; i += 4) d[i] = Math.max(0, Math.min(255, (d[i] - 128) * 4 + 128)); ctx.putImageData(id, 0, 0); return Selection.orNull(c); } /** Hard-threshold the mask (removes antialiasing / feathering). */ hardened() { const c = cloneCanvas(this.mask); const ctx = c.getContext('2d'); const id = ctx.getImageData(0, 0, c.width, c.height); const d = id.data; for (let i = 3; i < d.length; i += 4) d[i] = d[i] >= 128 ? 255 : 0; ctx.putImageData(id, 0, 0); return Selection.orNull(c); } static orNull(mask) { const s = new Selection(mask); return s.isEmpty ? null : s; } static all(w, h) { const c = createCanvas(w, h); const ctx = c.getContext('2d'); ctx.fillStyle = '#000'; ctx.fillRect(0, 0, w, h); return new Selection(c); } /** Selection from the alpha channel of a canvas (e.g. "select layer pixels"). */ static fromAlpha(canvas) { const c = createCanvas(canvas.width, canvas.height); c.getContext('2d').drawImage(canvas, 0, 0); return Selection.orNull(c); } } /** * Combine an existing selection with a newly drawn shape mask. * mode: 'replace' | 'add' | 'subtract' | 'intersect' */ export function combineSelection(current, shapeMask, mode) { if (mode === 'replace' || !current) { if (mode === 'subtract' || mode === 'intersect') return mode === 'intersect' ? null : current; return Selection.orNull(shapeMask); } const c = cloneCanvas(current.mask); const ctx = c.getContext('2d'); ctx.globalCompositeOperation = mode === 'add' ? 'source-over' : mode === 'subtract' ? 'destination-out' : 'destination-in'; ctx.drawImage(shapeMask, 0, 0); return Selection.orNull(c); } /** Build a shape mask canvas. shape: {type:'rect'|'ellipse'|'polygon', ...} */ export function shapeMask(w, h, shape, antialias = true) { const c = createCanvas(w, h); const ctx = c.getContext('2d'); ctx.fillStyle = '#000'; if (shape.type === 'rect') { const x = Math.round(shape.x), y = Math.round(shape.y); ctx.fillRect(x, y, Math.round(shape.x + shape.w) - x, Math.round(shape.y + shape.h) - y); return c; } ctx.beginPath(); if (shape.type === 'ellipse') { ctx.ellipse(shape.x + shape.w / 2, shape.y + shape.h / 2, Math.abs(shape.w / 2), Math.abs(shape.h / 2), 0, 0, Math.PI * 2); } else if (shape.type === 'polygon') { shape.points.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y))); ctx.closePath(); } ctx.fill('evenodd'); if (!antialias) { const id = ctx.getImageData(0, 0, w, h); const d = id.data; for (let i = 3; i < d.length; i += 4) d[i] = d[i] >= 128 ? 255 : 0; ctx.putImageData(id, 0, 0); } return c; }