LoginSignup
1
1

More than 1 year has passed since last update.

ランダムなカラーコード(RGBと16進数)を取得する方法

Posted at

16進数とMath.random()を理解する助けになったので覚書です。

16進数のカラーコード生成
var hex_numbers =  ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];
var hex = "";

for(var i = 0; i < 6; i++) {
  hex += hex_numbers[Math.floor(Math.random() * hex_numbers.length)];
}

var color_code = `#${hex}`;
RGBのカラーコード生成
var rgbArr = [];

for(var i = 0; i < 3; i++) {
  rgbArr.push(Math.floor(Math.random() * 256));
}

var color_code = `rgb(${rgbArr[0]}, ${rgbArr[1]}, ${rgbArr[2]})`

参考サイト

RGB→16進数、16進数→RGBの変換は下記が参考になりました。

1
1
2

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
1
1