| 1 | /** |
| 2 | * Average colour of a sprite's visible pixels. |
| 3 | * |
| 4 | * Pixels with alpha less than or equal to {@link AVERAGE_COLOR_ALPHA_THRESHOLD} |
| 5 | * are treated as transparent and do not affect the average. That drops fully |
| 6 | * transparent texels and the faintest antialias fringe (~6% opacity), while |
| 7 | * still counting visibly translucent pixels. |
| 8 | * |
| 9 | * Surviving pixels are weighted equally: alpha is a mask, not a weight. |
| 10 | * Callers pass the whole texture, so every frame of a spritesheet is included. |
| 11 | */ |
| 12 | export const AVERAGE_COLOR_ALPHA_THRESHOLD = 16; |
| 13 | |
| 14 | /** |
| 15 | * Arithmetic mean RGB of pixels whose alpha is above the threshold. |
| 16 | * @param {Uint8Array | Uint8ClampedArray} rgba |
| 17 | * @param {number} width |
| 18 | * @param {number} height |
| 19 | * @param {{ alphaThreshold?: number }} [options] |
| 20 | * @returns {{ r: number, g: number, b: number } | null} 0–255 channels, or null when nothing is visible |
| 21 | */ |
| 22 | export function averageOpaqueColor (rgba, width, height, options = {}) |
| 23 | { |
| 24 | const threshold = options.alphaThreshold ?? AVERAGE_COLOR_ALPHA_THRESHOLD; |
| 25 | const pixels = Math.max(0, width | 0) * Math.max(0, height | 0); |
| 26 | let red = 0; |
| 27 | let green = 0; |
| 28 | let blue = 0; |
| 29 | let count = 0; |
| 30 | for (let i = 0; i < pixels; i++) |
| 31 | { |
| 32 | const offset = i * 4; |
| 33 | const alpha = rgba[offset + 3] ?? 0; |
| 34 | if (alpha <= threshold) |
| 35 | { continue; } |
| 36 | red += rgba[offset] ?? 0; |
| 37 | green += rgba[offset + 1] ?? 0; |
| 38 | blue += rgba[offset + 2] ?? 0; |
| 39 | count += 1; |
| 40 | } |
| 41 | if (count === 0) |
| 42 | { return null; } |
| 43 | return { |
| 44 | r: Math.round(red / count), |
| 45 | g: Math.round(green / count), |
| 46 | b: Math.round(blue / count) |
| 47 | }; |
| 48 | } |