You can use a jQuery plugin called Color Thief.
- jquery.js (is included in WordPress)
- quantize.js (download from color-thief github page)
- color-thief.js (download from color-thief github page)
functions.php (located in your theme's folder) and add the code below to load the files in WordPress. In this case I placed all files in the "js" folder.
//color thief demo
wp_register_script('quantize', $base . '/js/quantize.js');
wp_register_script('colorThief', $base . '/js/color-thief.js');
wp_register_script('main', $base . '/js/main.js');
As you can see I also created a
main.js file to store the code that will run the color-thief code.
// Dominant Color
var dominantColor = getDominantColor($(this));
The code above will look for an image with
id = target.
load() function will ensure that the image has already loaded before the code is executed.
Next the value of the dominant color is stored in a variable (the value returned is 3 numbers, which form the RGB color)
We use that same variable to change the color of the background.
The HTML setup:
The TwentyEleven theme loads the image through a function in the file
header.php, but you can still edit the image tag and add an image ID to be able to find it easily with jQuery.
In this case my image ID is
src="<?php header_image(); ?>"
width="<?php echo HEADER_IMAGE_WIDTH; ?>"
height="<?php echo HEADER_IMAGE_HEIGHT; ?>"
And that should do it. Once the page loads, the jQuery script will look for an image with
id = target. Get the dominant color of that image, and then apply it to the background of the page automatically.
You can see a demo of this working here. (refresh the page a few times to until it loads a different image)