Installation
npm i @rtcoder/dominant-color
Imports
Use ESM in modern apps:
import { getDominantColor, getDominantColorAsync } from '@rtcoder/dominant-color';
CommonJS consumers can use require:
const { getDominantColor } = require('@rtcoder/dominant-color');
Usage
Promise-based API:
const img = document.querySelector('img');
const result = await getDominantColorAsync(img, {
colorFormat: 'hex',
colorQuantization: 'median-cut',
colorsPaletteLength: 6,
});
console.log(result.dominant, result.colorsPalette);
Callback API:
getDominantColor(img, {
colorFormat: 'rgb',
callback: (dominant, colorsPalette) => {
console.log(dominant, colorsPalette);
},
errorCallback: (error) => {
console.error(error);
},
});
Image sources
DOM and canvas
HTMLImageElement, HTMLCanvasElement, and ImageBitmap can be passed directly.
Files and URLs
Use URL strings, Blob, or File. Blob object URLs are created and revoked internally.
Options
| Name | Type | Default | Description |
|---|---|---|---|
downScaleFactor |
number | 1 | Scales the source down before sampling. Useful for large images. |
skipPixels |
number | 0 | Skips every n pixels while reading image data. |
colorsPaletteLength |
number | 5 | Maximum number of colors returned in the palette. |
colorQuantization |
'exact' | 'bucket' | 'median-cut' |
'exact' |
Controls palette extraction. median-cut is best for balanced photo palettes. |
colorBucketSize |
number | 24 | Bucket size used by colorQuantization: 'bucket'. |
colorGroupingThreshold |
number | 0 | Groups nearby RGB values after counting or quantization. |
paletteWithCountOfOccurrences |
boolean | false | Returns palette entries as { color, count }. |
colorFormat |
'rgb' | 'hsl' | 'hex' |
'rgb' |
Formats the dominant color and palette colors. |
callback |
function | empty function | Receives dominant and colorsPalette. |
errorCallback |
function | empty function | Receives image loading, canvas, and processing errors. |
Types
type ColorFormat = 'rgb' | 'hsl' | 'hex';
type ColorQuantization = 'exact' | 'bucket' | 'median-cut';
type DominantColorSource = HTMLImageElement | HTMLCanvasElement | ImageBitmap | string | Blob;
interface PrimaryColor {
color: string;
count: number;
}
interface DominantColorResult {
dominant: string;
colorsPalette: string[] | PrimaryColor[];
}
function getDominantColor(
source: DominantColorSource,
options?: Partial<DominantColorOptions>
): void;
function getDominantColorAsync(
source: DominantColorSource,
options?: Partial<DominantColorOptions>
): Promise<DominantColorResult>;