Change background color with a dominant from picture

Im looking for a smart way to change the background color for a page, but taking the #xxxxxx value from the dominant color of the headline picture.

In twenty eleven theme, I can set a random image for each page loaded, I would change the background color to match the picture.

Read More

I know that’s possible but I don’t know how to modify the CSS or the template to take the value from a specific function (I found this that seems promising:

https://stackoverflow.com/questions/2541481/get-average-color-of-image-via-javascript

Is that too complicated?

thanks alot

Related posts

Leave a Reply

1 comment

  1. You can use a jQuery plugin called Color Thief.

    Files needed:

    1. jquery.js (is included in WordPress)
    2. quantize.js (download from color-thief github page)
    3. color-thief.js (download from color-thief github page)

    WordPress setup:

    Open 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_enqueue_script('quantize');
    
    wp_register_script('colorThief', $base . '/js/color-thief.js');
    wp_enqueue_script('colorThief');
    
    wp_register_script('main', $base . '/js/main.js');
    wp_enqueue_script('main');
    

    As you can see I also created a main.js file to store the code that will run the color-thief code.

    main.js code:

    jQuery(document).ready(function($) {
    
        $("#target").load(function(){
    
            // Dominant Color
            var dominantColor = getDominantColor($(this));
    
            //change background
            $("body").css("background-color", "rgb("+dominantColor+")");
        });        
    });
    

    The code above will look for an image with id = target.
    The 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 target:

    <img 
        src="<?php header_image(); ?>" 
        width="<?php echo HEADER_IMAGE_WIDTH; ?>" 
        height="<?php echo HEADER_IMAGE_HEIGHT; ?>" 
        alt="" 
        id="target" />
    

    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)