/** * Average colour of a sprite's visible pixels. * * Pixels with alpha less than or equal to {@link AVERAGE_COLOR_ALPHA_THRESHOLD} * are treated as transparent and do not affect the average. That drops fully * transparent texels and the faintest antialias fringe (~6% opacity), while * still counting visibly translucent pixels. * * Surviving pixels are weighted equally: alpha is a mask, not a weight. * Callers pass the whole texture, so every frame of a spritesheet is included. */ export const AVERAGE_COLOR_ALPHA_THRESHOLD = 16; /** * Arithmetic mean RGB of pixels whose alpha is above the threshold. * @param {Uint8Array | Uint8ClampedArray} rgba * @param {number} width * @param {number} height * @param {{ alphaThreshold?: number }} [options] * @returns {{ r: number, g: number, b: number } | null} 0–255 channels, or null when nothing is visible */ export function averageOpaqueColor (rgba, width, height, options = {}) { const threshold = options.alphaThreshold ?? AVERAGE_COLOR_ALPHA_THRESHOLD; const pixels = Math.max(0, width | 0) * Math.max(0, height | 0); let red = 0; let green = 0; let blue = 0; let count = 0; for (let i = 0; i < pixels; i++) { const offset = i * 4; const alpha = rgba[offset + 3] ?? 0; if (alpha <= threshold) { continue; } red += rgba[offset] ?? 0; green += rgba[offset + 1] ?? 0; blue += rgba[offset + 2] ?? 0; count += 1; } if (count === 0) { return null; } return { r: Math.round(red / count), g: Math.round(green / count), b: Math.round(blue / count) }; }