LoginSignup
18
11

More than 5 years have passed since last update.

カラーコードのランダム生成で注意すること

Last updated at Posted at 2017-08-02

JavaScriptでカラーコードをランダムに生成して表示するコードを書いたら、なんかやたらと白い。

let r = Math.floor(Math.random() * 255).toString(16);
let g = Math.floor(Math.random() * 255).toString(16);
let b = Math.floor(Math.random() * 255).toString(16);
let color = '#' + r + g + b;

image.png

よくよく調べてみると、白くなっているところのカラーコードは#412bfのようになってました。
16進数に変換した結果が1桁である数値がrgbのいずれかに含まれている場合に、カラーコードの仕様を満たさず、白になってしまっていたようです。

以下のようにして解決。

let r = ('0' + Math.floor(Math.random() * 255).toString(16)).slice(-2);
let g = ('0' + Math.floor(Math.random() * 255).toString(16)).slice(-2);
let b = ('0' + Math.floor(Math.random() * 255).toString(16)).slice(-2);
let color = '#' + r + g + b;

rgbの各値に0を頭につけてslice(-2)で後ろ2文字をとることで強制的に2桁にしています。

image.png

rgbで書く方法

@yama-t 様からのコメントで以下のようにrgbの形式を使うと、桁揃えしなくてもいいという意見をいただきました(ありがとうございます!)。
テンプレートリテラルも使うとさらにすっきり書けるとのこと。

let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
let color = `rgb(${r},${g},${b})`;
18
11
5

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
18
11