fast-average-color

repository·master·Indexed 23 days ago

https://github.com/fast-average-color/fast-average-color

A high-performance library for calculating the average or dominant color of images, videos, and canvases in browser environments. Version 9.5.2 supports multiple algorithms (simple, sqrt, dominant) and various input types including HTMLImageElement, HTMLCanvasElement, OffscreenCanvas, ImageBitmap, VideoFrame, and raw pixel arrays. It provides synchronous and asynchronous methods to extract colors in RGB, RGBA, HEX, and HEXA formats, with built-in support for transparency and color exclusion.

Tokens
5.2K
Snippets
13
Records
26
Agent score
80%

What's inside fast-average-color

  1. Overview of Fast Average Color

    master

    fast-average-color is a lightweight library designed to calculate the average or dominant color of images or videos in a browser environment. It is optimized for speed and supports various input types including images, videos, canvases, and raw pixel data.

    Key Features

    • High Performance: Optimized for speed.
    • Multiple Algorithms: Supports simple, sqrt (default), and dominant algorithms.
    • Versatile Inputs: Works with HTMLImageElement, video, HTMLCanvasElement, OffscreenCanvas, ImageBitmap, VideoFrame, and raw pixel arrays (Uint8Array, Uint8ClampedArray, or arrays of numbers).
    • Advanced Capabilities: Supports transparency (PNG, SVG), specific resource regions, and Web Workers.
    • Small Footprint: Small bundle size and supports tree shaking.
  2. Choose an averaging algorithm

    master

    The fast-average-color library provides three different algorithms to calculate the average color of an image. You can specify which algorithm to use by passing the algorithm option to the getColor method.

    Available algorithms:

    • sqrt (default): Uses a square root approach for color calculation.
    • simple: A simpler, faster averaging method.
    • dominant: A more complex algorithm designed to find the most dominant color in an image.
    const fac = new FastAverageColor();
    console.log(fac.getColor(image, {algorithm: 'dominant'});
  3. Use fast-average-color with CommonJS

    master

    In a CommonJS environment, import the FastAverageColor class from the package.

    'use strict';
    
    const FastAverageColor = require('fast-average-color').FastAverageColor;
    const fac = new FastAverageColor();
    
    fac.getColorAsync(container.querySelector('img'))
        .then(color => {
            container.style.backgroundColor = color.rgba;
            container.style.color = color.isDark ? '#fff' : '#000';
        })
        .catch(e => {
            console.log(e);
        });
  4. Use fast-average-color with ES Modules or TypeScript

    master

    In ES Modules or TypeScript environments, use a named import for FastAverageColor.

    import { FastAverageColor } from 'fast-average-color';
    
    const fac = new FastAverageColor();
    fac.getColorAsync(container.querySelector('img'))
        .then(color => {
            container.style.backgroundColor = color.rgba;
            container.style.color = color.isDark ? '#fff' : '#000';
        })
        .catch(e => {
            console.log(e);
        });
  5. Set up the development environment

    master

    To contribute to or develop the fast-average-color project locally, clone the repository, install the dependencies using npm i, and run the test suite using npm test to ensure the environment is correctly configured.

    git clone git@github.com:fast-average-color/fast-average-color.git ./fast-average-color
    cd ./fast-average-color
    
    npm i
    npm test
  6. Use fast-average-color in the Browser

    master

    You can use the library directly in the browser by including the minified script from unpkg. The FastAverageColor class is available on the global scope. Use getColorAsync() to extract color information from an image element.

    <script src="https://unpkg.com/fast-average-color/dist/index.browser.min.js"></script>
    <script>
        const fac = new FastAverageColor();
        const container = document.querySelector('.image-container');
    
        fac.getColorAsync(container.querySelector('img'))
            .then(color => {
                container.style.backgroundColor = color.rgba;
                container.style.color = color.isDark ? '#fff' : '#000';
            })
            .catch(e => {
                console.log(e);
            });
    </script>
  7. Understand the FastAverageColorResult object

    master

    The FastAverageColorResult is the standard output format for color extraction. It provides the color in multiple formats and metadata about its brightness.

    Fields:

    • value: The color as an array of 4 numbers [r, g, b, a] (0-255).
    • rgb: A CSS-compatible string: rgb(r,g,b).
    • rgba: A CSS-compatible string: rgba(r,g,b,a) (where a is 0-1).
    • hex: The color in hex format (e.g., #RRGGBB).
    • hexa: The color in hex format including alpha (e.g., #RRGGBBAA).
    • isDark: true if the color is considered dark.
    • isLight: true if the color is considered light.
    • error: An Error object if the operation failed, otherwise undefined.
  8. Supported resource types for color extraction

    master

    The FastAverageColorResource type defines the valid inputs that can be passed to the library for color extraction. Supported types include:

    • HTMLImageElement
    • HTMLVideoElement
    • HTMLCanvasElement
    • OffscreenCanvas
    • ImageBitmap
    • VideoFrame
    • null (which typically triggers the use of defaultColor)
  9. Handling CORS SecurityErrors with external images

    master

    When attempting to extract colors from images hosted on a different origin, you may encounter a SecurityError: The operation is insecure. This happens because using images from external origins without CORS approval 'taints' the canvas, preventing data extraction.

    To prevent this, ensure the image element has the crossorigin attribute set to "anonymous" before loading the source.

  10. Ignore specific colors using ignoredColor

    master

    You can exclude certain colors from the average calculation by passing an ignoredColor option to getColorAsync. This is useful for ignoring backgrounds (like white or black) in logos.

    • To ignore a single color, provide an array: [r, g, b, a].
    • To ignore multiple colors, provide an array of arrays: [[r, g, b, a], [r, g, b, a]].
    • To ignore a color within a certain tolerance, provide an array with a threshold: [r, g, b, a, threshold].
    const fac = new FastAverageColor();
    
    // Ignore a single white color
    fac.getColorAsync('./logo.png', {
        ignoredColor: [255, 255, 255, 255]
    });
    
    // Ignore multiple colors (white and black)
    fac.getColorAsync('./logo.png', {
        ignoredColor: [
            [255, 255, 255, 255], // white
            [0, 0, 0, 255]        // black
        ]
    });
    
    // Ignore a color with a threshold
    fac.getColorAsync('./logo.png', {
        ignoredColor: [
            // [red, green, blue, alpha, threshold]
            [255, 0, 100, 255, 5]
        ],
    });