Color Theory
September 17, 2025·7 min read

Palette Extraction with K-Means Clustering on Canvas

Implementing dominant color extraction from images using K-Means clustering in the browser.

NA

Naushad Alam

Contributing Author · Squoosh Next Blog

Extracting a dominant color palette from an image is a fundamental requirement for design tools, e-commerce product pages, and dynamic theme generation. The standard approach is K-Means clustering applied to the pixel color space. The algorithm initializes K cluster centroids (typically 6–8 for a palette), assigns each pixel to its nearest centroid using Euclidean distance in RGB space, then recalculates centroids as the mean of assigned pixels.

This process repeats until centroids stabilize. On the Canvas API, you first read the ImageData for a downscaled version of the image to reduce computation, then run K-Means on the color samples. A practical optimization is to quantize each channel to 8 levels first, reducing the color space from 16 million to 512 unique values, making the clustering dramatically faster.

The result is a palette that accurately represents the perceptually prominent colors in the image.

Key Takeaways
  • Extracting a dominant color palette from an image is a fundamental requirement for design tools, e-commerce product pages, and dynamic theme generation.

  • The standard approach is K-Means clustering applied to the pixel color space.

  • The algorithm initializes K cluster centroids (typically 6–8 for a palette), assigns each pixel to its nearest centroid using Euclidean distance in RGB space, then recalculates centroids as the mean of assigned pixels.

  • This process repeats until centroids stabilize.

Try It in the Workspace

Everything discussed in this article can be tested directly in Squoosh Next — no sign-up, no upload, 100% client-side.

More in Color Theory
Understanding Chroma Subsampling in MozJPEG
June 08, 2026 · 8 min read
Color Spaces 101: sRGB vs Display P3
February 24, 2026 · 6 min read
Color Grading Presets: The Science of Cinematic Looks
July 03, 2024 · 8 min read
Squoosh Next

Professional client-side image compression and format optimization tool. Compress, convert, and adjust 100+ formats instantly without server uploads.


© 2026 Squoosh Next. Developed & Maintained by Naushad Alam | Zest Tech Solution | Powered by Vercel.Contact: Naushad Alam | WhatsApp: 7492068998 | Email: contact@zestcommerce.in | Web: zesttechsolution.cloud
Security EncryptedNo Uploads
Operational
v2.1.0Commit: d05d63e
0s
Build Info
Environment: productionBranch: masterBuild Time: 25s
Deployment
Deployed: 7/13/2026, 1:29:19 AMUptime: 0sPlatform: Vercel
Performance
Response: 0msStatus: OnlineSSL: Active
Technology
Next.js: 16.2.9React: 19.0.0TypeScript: 5.0