diff --git a/dither-image.js b/dither-image.js index 422686c..618b884 100644 --- a/dither-image.js +++ b/dither-image.js @@ -617,8 +617,23 @@ function decimate(input, palette, n) { ); }); let topRanges = ranges.map((rgb) => Math.max(rgb.r, rgb.g, rgb.b)); - let greatest = Math.max(...topRanges); - let index = topRanges.indexOf(greatest); + //let greatest = Math.max(...topRanges); + //let index = topRanges.indexOf(greatest); + let greatest = 0; + let index = -1; + for (let i = 0; i < topRanges.length; i++) { + if (topRanges[i] >= greatest) { + greatest = topRanges[i]; + index = i; + } + } + if (index == -1) { + // We just ran out of colors! Pad the buckets. + while (buckets.length < n) { + buckets.push([new RGB(0, 0, 0)]); + } + break; + } let [lo, hi] = medianCut(buckets[index], ranges[index]); buckets.splice(index, 1, lo, hi); }