3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

#rrggbb やカラーキーワード("red", "navy")など様々な色指定からRGBを導出する

Last updated at Posted at 2014-08-15

CSS の色指定はいろんな方法ができていて、そこからRGBを求めるのには一筋縄では行かない感じがあるので、それを何とかする方法。

これができると、こういうことができるので別で書いた。

問題

#rrggbbrgba(...) だけならパースすれば良さそうだけれど、black, red など カラーキーワードによる指定はたくさん種類がある ので入力が面倒。

解決方法

なので一度、不可視な canvas に対象の色を置いてしまってRGBをとる:

// 与えられた色指定文字列から、RGB(ついでにアルファ)を返す
function getRgbaFromString(colorString) {
    var canvas = document.createElement('canvas');
    canvas.width = 1; canvas.height = 1;
    
    var c = canvas.getContext('2d');
    c.fillStyle = colorString;
    c.fillRect(0, 0, 1, 1);

    var d = c.getImageData(0, 0, 1, 1).data;
    return {
        red: d[0],
        green: d[1],
        blue: d[2],
        alpha: d[3]
    };
}

使ってみる:

['black', 'cyan', 'rgb(123, 23, 0)',
 '#3399ff', 'rgba(255, 255, 255, 0.6)'
].forEach(function(e) {
    var o = getRgbaFromString(e);
    var a = [o.red, o.green, o.blue, o.alpha]
    console.log('%s:\t%s', e, a.join(', '));
})
black:	0, 0, 0, 255
burlywood:	222, 184, 135, 255
rgb(123, 23, 0):	123, 23, 0, 255
# 3399ff:	51, 153, 255, 255
rgba(255, 255, 255, 0.6):	255, 255, 255, 153 

できてるっぽい。

呼び出し頻度が多いなら、毎回 canvas 要素を作るのはやめた方が良さそう。

注意

ただこのやり方は:

  • canvas が解釈するカラーキーワード
  • HTML/CSS が解釈するキーワード

の2つが同じものであるという仮定に基づいているので、2つにズレがあると思ったとおりに動かない。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?