Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Grabs the dominant colour or a representative colour palette from an uploaded image. Uses JavaScript and Canvas.

Notifications You must be signed in to change notification settings

achudars/color-thief

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

91 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Color Thief - Modern Edition*

npm version License: CC BY 2.5

A modern, fast JavaScript library for extracting dominant colors and color palettes from images. Built with ES6+ features and optimized for modern browsers.

*With additional upload functionality, so now it provides you the possibility to try this plugin to see if it fits your needs. -Aleks

See a Demo | Read more on Lokesh's blog | Try the Modern Version

Color Thief Demo

✨ Features

  • 🎨 Advanced Algorithm: Uses modified median cut quantization (MMCQ) for accurate color extraction
  • ⚑ Modern Performance: Built with ES6+ features, optimized for speed
  • πŸ“± Responsive: Works on desktop, tablet, and mobile devices
  • πŸ”— Easy Integration: Simple API that works with any image source
  • πŸŒ™ Dark Mode: Automatic dark mode support
  • β™Ώ Accessible: Built with accessibility in mind
  • πŸ“¦ Tree Shakable: ES modules for optimal bundle size

πŸš€ Quick Start

Installation

npm install color-thief-modern

Basic Usage

import { ColorThief } from 'color-thief-modern';

// Get dominant color
const dominantColor = ColorThief.getDominantColor(imageElement);
// Returns: [r, g, b] array

// Get color palette
const palette = ColorThief.getPalette(imageElement, 8);
// Returns: [[r,g,b], [r,g,b], ...] array

// Convert to hex
const hexColor = ColorThief.rgbToHex(dominantColor);
// Returns: "#ff5733"

// Convert to HSL
const hslColor = ColorThief.rgbToHsl(dominantColor);
// Returns: [h, s, l] array

HTML Usage

<!DOCTYPE html>
<html>
  <head>
    <script type="module">
      import { ColorThief } from './path/to/color-thief.js';

      const img = document.getElementById('myImage');
      img.addEventListener('load', function () {
        const dominantColor = ColorThief.getDominantColor(this);
        console.log('Dominant color:', dominantColor);
      });
    </script>
  </head>
  <body>
    <img id="myImage" src="image.jpg" crossorigin="anonymous" />
  </body>
</html>

πŸ“– API Reference

ColorThief.getDominantColor(image, quality?)

Returns the dominant color from an image. Uses the median cut algorithm provided by quantize.js to cluster similar colors and return the base color from the largest cluster.

Parameters:

  • image (HTMLImageElement|HTMLCanvasElement): The source image
  • quality (number, optional): Quality/speed trade-off (1-10, default: 10)

Returns: number[]|null - RGB array [r, g, b] or null if failed

ColorThief.getPalette(image, colorCount?, quality?)

Returns a color palette from an image. Uses the median cut algorithm provided by quantize.js to cluster similar colors.

Parameters:

  • image (HTMLImageElement|HTMLCanvasElement): The source image
  • colorCount (number, optional): Number of colors to extract (2-20, default: 10)
  • quality (number, optional): Quality/speed trade-off (1-10, default: 10)

Returns: number[][]|null - Array of RGB arrays [[r,g,b], ...] or null if failed

Legacy API (Backward Compatibility)

The original function names are still available as named exports:

import { getDominantColor, createPalette } from 'color-thief-modern';

// Original API still works
getDominantColor(sourceImage); // Returns [num, num, num]
createPalette(sourceImage, colorCount); // Returns [[num, num, num], ...]

ColorThief.getAverageColor(image, sampleSize?)

Returns the average color from an image.

Parameters:

  • image (HTMLImageElement|HTMLCanvasElement): The source image
  • sampleSize (number, optional): Pixel sampling rate (default: 10)

Returns: number[]|null - RGB array [r, g, b] or null if failed

ColorThief.rgbToHex(rgb)

Converts RGB array to hex string.

Parameters:

  • rgb (number[]): RGB array [r, g, b]

Returns: string - Hex color string (e.g., "#ff5733")

ColorThief.rgbToHsl(rgb)

Converts RGB array to HSL array.

Parameters:

  • rgb (number[]): RGB array [r, g, b]

Returns: number[] - HSL array [h, s, l]

πŸ› οΈ Development

Prerequisites

  • Node.js 16+
  • npm or yarn

Setup

# Clone the repository
git clone https://github.com/achudars/color-thief.git
cd color-thief

# Install dependencies
npm install

# Start development server
npm run dev

# Build for production
npm run build

# Run linting
npm run lint

# Format code
npm run format

Project Structure

β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ color-thief.js     # Main library
β”‚   β”œβ”€β”€ quantize.js        # Color quantization algorithm
β”‚   β”œβ”€β”€ main.js           # Demo application
β”‚   └── styles.css        # Modern CSS styles
β”œβ”€β”€ public/               # Static assets
β”œβ”€β”€ dist/                # Built files
β”œβ”€β”€ index.html           # Modern demo page
β”œβ”€β”€ package.json
β”œβ”€β”€ vite.config.js       # Vite configuration
β”œβ”€β”€ eslint.config.js     # ESLint configuration
└── .prettierrc          # Prettier configuration

🌟 Improvements Over Original

Modern JavaScript Features

  • βœ… ES6+ classes and modules
  • βœ… Async/await and Promises
  • βœ… Optional chaining and nullish coalescing
  • βœ… Template literals and destructuring
  • βœ… Arrow functions and const/let

Performance Optimizations

  • βœ… Improved algorithm efficiency
  • βœ… Better memory management
  • βœ… Reduced DOM manipulation
  • βœ… Tree-shakable modules

Developer Experience

  • βœ… TypeScript-like JSDoc annotations
  • βœ… Modern build system (Vite)
  • βœ… ESLint and Prettier configuration
  • βœ… Better error handling and validation

User Experience

  • βœ… Drag & drop file upload
  • βœ… Click to copy colors
  • βœ… Responsive design
  • βœ… Dark mode support
  • βœ… Accessibility improvements

πŸ”§ Browser Support

  • Chrome 61+
  • Firefox 60+
  • Safari 12+
  • Edge 79+

πŸ“„ License

By Lokesh Dhakar | lokeshdhakar.com | twitter.com/lokeshdhakar
Modernized by Aleksandrs Cudars with additional upload functionality

Thanks to Nick Rabinowitz for creating quantize.js which provides the MMCQ algorithm, jfsiii for a large number of code improvements, and others for submitting issues and fixes.

Licensed under the Creative Commons Attribution 2.5 License

  • βœ… Free for use in both personal and commercial projects
  • βœ… Attribution required: Leave author name, author homepage link, and the license info intact

Links

About

Grabs the dominant colour or a representative colour palette from an uploaded image. Uses JavaScript and Canvas.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 79.1%
  • CSS 13.9%
  • HTML 7.0%