Skip to content

Commit 765cb91

Browse files
committed
inline alpha blending
1 parent 062d5bb commit 765cb91

File tree

1 file changed

+23
-34
lines changed

1 file changed

+23
-34
lines changed

index.js

Lines changed: 23 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -171,36 +171,30 @@ function hasManySiblings(img, x1, y1, width, height) {
171171
// using YIQ NTSC transmission color space in mobile applications" by Y. Kotsarenko and F. Ramos
172172

173173
function colorDelta(img1, img2, k, m, yOnly) {
174-
let r1 = img1[k];
175-
let g1 = img1[k + 1];
176-
let b1 = img1[k + 2];
177-
let a1 = img1[k + 3];
178-
179-
let r2 = img2[m];
180-
let g2 = img2[m + 1];
181-
let b2 = img2[m + 2];
182-
let a2 = img2[m + 3];
183-
184-
if (a1 === a2 && r1 === r2 && g1 === g2 && b1 === b2) return 0;
185-
186-
if (a1 < 255) {
187-
a1 /= 255;
188-
r1 = blend(r1, a1);
189-
g1 = blend(g1, a1);
190-
b1 = blend(b1, a1);
174+
const r1 = img1[k];
175+
const g1 = img1[k + 1];
176+
const b1 = img1[k + 2];
177+
const a1 = img1[k + 3];
178+
const r2 = img2[m];
179+
const g2 = img2[m + 1];
180+
const b2 = img2[m + 2];
181+
const a2 = img2[m + 3];
182+
183+
let dr = r1 - r2;
184+
let dg = g1 - g2;
185+
let db = b1 - b2;
186+
187+
if (a1 === a2 && !dr && !dg && !db) return 0;
188+
189+
if (a1 < 255 || a2 < 255) { // blend pixels with background
190+
const rb = 255;
191+
const gb = 255;
192+
const bb = 255;
193+
dr = ((r1 - rb) * a1 - (r2 - rb) * a2) / 255;
194+
dg = ((g1 - gb) * a1 - (g2 - gb) * a2) / 255;
195+
db = ((b1 - bb) * a1 - (b2 - bb) * a2) / 255;
191196
}
192197

193-
if (a2 < 255) {
194-
a2 /= 255;
195-
r2 = blend(r2, a2);
196-
g2 = blend(g2, a2);
197-
b2 = blend(b2, a2);
198-
}
199-
200-
const dr = r1 - r2;
201-
const dg = g1 - g2;
202-
const db = b1 - b2;
203-
204198
const y = dr * 0.29889531 + dg * 0.58662247 + db * 0.11448223;
205199

206200
if (yOnly) return y; // brightness difference only
@@ -214,11 +208,6 @@ function colorDelta(img1, img2, k, m, yOnly) {
214208
return y > 0 ? -delta : delta;
215209
}
216210

217-
// blend semi-transparent color with white
218-
function blend(c, a) {
219-
return 255 + (c - 255) * a;
220-
}
221-
222211
function drawPixel(output, pos, r, g, b) {
223212
output[pos + 0] = r;
224213
output[pos + 1] = g;
@@ -230,6 +219,6 @@ function drawGrayPixel(img, i, alpha, output) {
230219
const r = img[i + 0];
231220
const g = img[i + 1];
232221
const b = img[i + 2];
233-
const val = blend(r * 0.29889531 + g * 0.58662247 + b * 0.11448223, alpha * img[i + 3] / 255);
222+
const val = 255 + (r * 0.29889531 + g * 0.58662247 + b * 0.11448223 - 255) * alpha * img[i + 3] / 255;
234223
drawPixel(output, i, val, val, val);
235224
}

0 commit comments

Comments
 (0)