3

I search a way to determine the real visible color of page elements. If i use JQuery i can do the following:

$('#foo').css('background-color');

But, the background-color of #foo may return "transparent" even if one of its parents declared a colored background. So, how do i get the correct color which is visible to end users (including half-transparency / RGBA)?

Update

I am using the Selenium2 Java API with Firefox 5. Maybe there is a way without JQuery, too. Involving Screenshots maybe?

Update 2

I rephrased and extended the question: Get dominating color of a specific area in an image: Color Query for Web Page Elements

Community
  • 1
  • 1
Alp
  • 29,274
  • 27
  • 120
  • 198
  • 1
    You can get the `background-color` property for that element, but you cannot get the calculated background colour. That's for the browser to render and can be complex what with transparency and gradients becoming popular. – Ben Everard Jul 08 '11 at 10:43
  • I use Selenium 2 with Firefox 5. Could there be another way to achieve this? – Alp Jul 08 '11 at 11:42

1 Answers1

4

You would need to traverse up the tree to find the element which has a background-color, one approach I did was like this (where textureEl is the element you want to check):

bgcolor = $(textureEl).css('background-color'); 
if (isTransparent(bgcolor)){
    $(textureEl).parents().each(function(){
        if (!isTransparent($(this).css('background-color'))){
            bgcolor = $(this).css('background-color');
            return false;
        }

    });
}

and

function isTransparent(bgcolor){
    return (bgcolor=="transparent" || bgcolor.substring(0,4) == "rgba");
}

but note that my isTransparent function made any non 100% opacity value marked as transparent, if you don't want that, then redefine what to do with rgba colors.

This of course doesn't take into account background-images either, but as your question didn't mention them, nor my application needed to take them into account, there isn't anything there to check for images.

Niklas
  • 29,752
  • 5
  • 50
  • 71
  • Thanks for your answer. Background images are interesting too, but i thought that would be too complex in the beginning. Your approach looks good, but better would be to compute the "real" visible color of half-transparent backgrounds. – Alp Jul 08 '11 at 11:44
  • @Alp To take into account colors with lower opacity than 1, you'd need to recalculate the color based on a mix of colors and their opacity, which would probably be far more complex than including images. The reason I didn't have images in my example was because in my application I rendered the images on top of the colors. – Niklas Jul 08 '11 at 11:48
  • So, are you talking about taking screen shots and getting the color of the specified location? – Alp Jul 08 '11 at 12:18