UNPKG

major-color-picker

Version:

major-color-picker is a lightweight JavaScript utility that detects the most dominant color from an image using the HTML Canvas API. Ideal for generating color palettes, styling backgrounds, or enhancing visual UI effects based on image content.

57 lines (56 loc) 2.7 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getDominantColorFromImage = getDominantColorFromImage; function getDominantColorFromImage(imgFile) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { const img = new Image(); const reader = new FileReader(); reader.onload = () => { img.src = reader.result; }; img.onload = () => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); if (!ctx) return reject('Canvas context not available'); canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0, img.width, img.height); const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const data = imageData.data; const colorMap = {}; let dominantColor = ''; let maxCount = 0; for (let i = 0; i < data.length; i += 4) { const r = data[i]; const g = data[i + 1]; const b = data[i + 2]; const key = `${r},${g},${b}`; colorMap[key] = (colorMap[key] || 0) + 1; if (colorMap[key] > maxCount) { maxCount = colorMap[key]; dominantColor = key; } } const [r, g, b] = dominantColor.split(',').map(Number); const hex = `#${r.toString(16).padStart(2, '0')}${g .toString(16) .padStart(2, '0')}${b.toString(16).padStart(2, '0')}`; resolve(hex); }; img.onerror = reject; reader.onerror = reject; reader.readAsDataURL(imgFile); }); }); }