---
title: "Advanced script to extract the dominant color and generate dynamic gradients"
url: "https://www.marrisonlab.com/advanced-script-to-extract-the-dominant-color-and-generate-dynamic-gradients/"
type: "post"
published: "2025-12-12T20:09:37+01:00"
modified: "2026-07-06T13:40:13+02:00"
author: "Angelo Marra"
---

## Dominant Color Extraction with Gradient

This JavaScript script analyzes an image to extract its dominant colors and applies a **dynamic gradient** to a container. The text color is automatically set based on the average contrast to ensure readability.

### Instructions for Use

1. Assign the ID “myImage” to the image widget and “targetDiv” to the container.
2. Paste the JavaScript script before the closing `</body>` tag or inside an HTML/JS widget.
3. The script will analyze the image, calculate the dominant colors, and apply the gradient to the target container.
4. It works best if the image is same-origin or if the server allows `Access-Control-Allow-Origin`.

Optional parameters in the script: sampling canvas size, color quantization level, brightness filters, and cluster size.

Result: the target container displays a gradient between the dominant colors of the image, with automatically readable text.
