Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

color scheme - Calculating contrasting colours in javascript

On one of pages we're currently working on users can change the background of the text displayed.

We would like to automatically alter the foreground colour to maintain reasonable contrast of the text.

We would also prefer the colour range to be discretionary. For example, if background is changing from white to black in 255 increments, we don't want to see 255 shades of foreground colour. In this scenario, perhaps 2 to 4, just to maintain reasonable contrast.

Any UI/design/colour specialists/painters out there to whip out the formula?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Basing your black-white decision off of luma works pretty well for me. Luma is a weighted sum of the R, G, and B values, adjusted for human perception of relative brightness, apparently common in video applications. The official definition of luma has changed over time, with different weightings; see here: http://en.wikipedia.org/wiki/Luma_(video). I got the best results using the Rec. 709 version, as in the code below. A black-white threshold of maybe 165 seems good.

function contrastingColor(color)
{
    return (luma(color) >= 165) ? '000' : 'fff';
}
function luma(color) // color can be a hx string or an array of RGB values 0-255
{
    var rgb = (typeof color === 'string') ? hexToRGBArray(color) : color;
    return (0.2126 * rgb[0]) + (0.7152 * rgb[1]) + (0.0722 * rgb[2]); // SMPTE C, Rec. 709 weightings
}
function hexToRGBArray(color)
{
    if (color.length === 3)
        color = color.charAt(0) + color.charAt(0) + color.charAt(1) + color.charAt(1) + color.charAt(2) + color.charAt(2);
    else if (color.length !== 6)
        throw('Invalid hex color: ' + color);
    var rgb = [];
    for (var i = 0; i <= 2; i++)
        rgb[i] = parseInt(color.substr(i * 2, 2), 16);
    return rgb;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...