简体   繁体   中英

Change the color of text depending of background image

I'm in need of a solution to my problem (if there is any):

I want to check the color value of the background image that is behind a div(in my case .picturecenter) then change the color from black to white if the value of the background is dark.

Is this possible?

Here is my site: http://myhrmans.com/hulebild2/ (the text "Welcome" is the target) I have looked at https://github.com/kennethcachia/Background-Check/ already and have not got it to work.

Thankful for any help!

You can pixel read with a canvas element. Check out the function here.

[get average color of image via javascript

You would have to deal with an image element and not a div element with an image background. But you could parse out the image src from the background

var bg = $('.picturecenter').css('background-image')

then just do some substring on the left and right parens to get the url. then get the raw javascript img element.

var imgElement = document.createElement('img');
imgElement.src = bg;

and call the method in the link above.

var colors = getAverageRGB(imgElement);

Then you could average the colors together to see if it's dark enough. something like

var avg = (colors.r + colors.g + colors.b) / 3;
if (avg < 100)
    $('.textcenter').css('color', '#EEE')
else
    $('.textcenter').css('color', '#333')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM