Created
April 24, 2013 12:47
-
-
Save fnobi/5451865 to your computer and use it in GitHub Desktop.
HTMLのカラーコードから、明度を出した話 ref: http://qiita.com/items/d3464ba0e4b6596863cb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var rgb = [128, 30, 200]; // R=128, G=30, B=200 | |
// 0〜255の値が入っているので、255で割っておく | |
var blightness = Math.max(rgb[0], rgb[1], rgb[2]) / 255; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 補正付きの明度取得 | |
var getBright = function (colorcode, mod) { | |
// 先頭の#は、あってもなくてもOK | |
if (colorcode.match(/^#/)) { | |
colorcode = colorcode.slice(1); | |
} | |
// 無駄に、ケタを動的に判断してるので、 | |
// 3の倍数ケタの16進数表現ならOK etc) #ff0000 #f00 #fff000000 | |
var keta = Math.floor(colorcode.length / 3); | |
if (keta < 1) { | |
return false; | |
} | |
// 16進数をparseして、RGBそれぞれに割り当て | |
var rgb = []; | |
for (var i = 0; i < 3; i++) { | |
rgb.push(parseInt(colorcode.slice(keta * i, keta * (i + 1)), 16)); | |
} | |
// 青は暗めに見えるなど、見え方はRGBそれぞれで違うので、 | |
// それぞれ補正値を付けて、人間の感覚に寄せられるようにした | |
var rmod = mod.r || 1; | |
var gmod = mod.g || 1; | |
var bmod = mod.b || 1; | |
// 明度 = RGBの最大値 | |
var bright = Math.max(rgb[0] * rmod, rgb[1] * gmod, rgb[2] * bmod) / 255; | |
// 明度を返す | |
return bright; | |
}; | |
// 補正はとりあえず、こんなもんがよさげだった | |
var mod = { r: 0.9, g: 0.8, b: 0.4 }; | |
getBright('#ffc300', mod); | |
// 薄い背景色なら黒文字、明るい背景色なら黒文字、とかに使う | |
getBright('', mod) > 0.5 ? 'black' : 'white' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment