aboutsummaryrefslogtreecommitdiff
path: root/build/js/core/selection.js
blob: a5333b165690fa0826a68f451b2f8495be97d725 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// 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;
}