【保存版】JavaScriptでランダムな色を生成する7つの方法!目的別で使い分け
JavaScript でランダムな色を生成するプログラミング
基本的な方法
最もシンプルな方法は、Math.random() 関数を使って、0から255までのランダムな値を3つ生成し、RGB形式で色を表現する方法です。
function getRandomColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
}
このコードを実行すると、毎回ランダムな色の値が生成されます。これを backgroundColor
プロパティなどに設定することで、要素にランダムな色を適用することができます。
const element = document.getElementById('myElement');
element.style.backgroundColor = getRandomColor();
16進数表記での表現
上記の方法ではRGB形式で色を表現していましたが、16進数表記の方がより簡潔に表現できます。
function getRandomColor() {
const r = Math.floor(Math.random() * 256).toString(16).padStart(2, '0');
const g = Math.floor(Math.random() * 256).toString(16).padStart(2, '0');
const b = Math.floor(Math.random() * 256).toString(16).padStart(2, '0');
return `#${r}${g}${b}`;
}
このコードでは、toString(16)
メソッドを使って16進数表記に変換し、padStart()
メソッドで不足している桁を0で補完しています。
特定の色味の範囲を生成
ランダムな色を生成する場合でも、特定の色味に偏った色を生成したい場合は、以下の方法で調整できます。
-
特定の色合いを中心とした範囲を生成:
function getRandomColorWithHue(hue) { const h = (hue + Math.random() * 30) % 360; const s = 0.5 + Math.random() * 0.5; const l = 0.5 + Math.random() * 0.5; return hslToRgb(h, s, l); }
このコードでは、
hslToRgb()
関数を使ってHSI形式からRGB形式に変換しています。HSI形式は、色相(Hue)、彩度(Saturation)、明度(Luminance)で色を表す形式です。 -
明暗を調整:
function getRandomColorWithBrightness(brightness) { const r = Math.floor(Math.random() * 256); const g = Math.floor(Math.random() * 256); const b = Math.floor(Math.random() * 256); const hsl = rgbToHsl(r, g, b); hsl.l = brightness; return hslToRgb(hsl.h, hsl.s, hsl.l); }
このコードでは、
rgbToHsl()
とhslToRgb()
関数を使って、RGB形式とHSI形式を相互に変換しています。
カラーパレットからランダムな色を選択
あらかじめ用意しておいたカラーパレットからランダムな色を選択する方法もあります。
const colors = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff'];
function getRandomColorFromPalette() {
const index = Math.floor(Math.random() * colors.length);
return colors[index];
}
このコードでは、配列 colors
にあらかじめ色を定義しています。ランダムなインデックスを使って配列から要素を取り出すことで、ランダムな色を選択することができます。
高度なテクニック
上記以外にも、様々な高度なテクニックを使ってランダムな色を生成することができます。
- 特定の色を避けながら生成: 除外したい色をリスト化しておき
JavaScript ランダムカラー生成 サンプルコード
基本的な方法
function getRandomColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
}
このコードを実行すると、毎回ランダムな色の値が生成されます。
16進数表記での表現
function getRandomColor() {
const r = Math.floor(Math.random() * 256).toString(16).padStart(2, '0');
const g = Math.floor(Math.random() * 256).toString(16).padStart(2, '0');
const b = Math.floor(Math.random() * 256).toString(16).padStart(2, '0');
return `#${r}${g}${b}`;
}
特定の色味の範囲を生成
function getRandomColorWithHue(hue) {
const h = (hue + Math.random() * 30) % 360;
const s = 0.5 + Math.random() * 0.5;
const l = 0.5 + Math.random() * 0.5;
return hslToRgb(h, s, l);
}
カラーパレットからランダムな色を選択
const colors = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff'];
function getRandomColorFromPalette() {
const index = Math.floor(Math.random() * colors.length);
return colors[index];
}
利用例
const element = document.getElementById('myElement');
element.style.backgroundColor = getRandomColor(); // 基本的な方法
const element2 = document.getElementById('myElement2');
element2.style.backgroundColor = getRandomColorWithHue(180); // 特定の色味の範囲
const element3 = document.getElementById('myElement3');
element3.style.backgroundColor = getRandomColorFromPalette(); // カラーパレットからランダム
これらのコードを参考に、様々なランダムカラー生成を試してみてください。
- 配列
colors
に好きな色を追加することで、カラーパレットをカスタマイズできます。 getRandomColorWithHue()
関数は、引数hue
を調整することで、赤系、青系、緑系など、特定の色味の範囲をさらに絞ることができます。- ランダムな色を生成する関数を自作することで、より複雑な条件に基づいた色生成が可能になります。
JavaScript でランダムな色を生成するその他の方法
HSL形式からランダムな色を生成
HSI(Hue, Saturation, Luminance)モデルは、色相、彩度、明度を使用して色を表現します。このモデルを使用すると、より直感的にランダムな色を生成することができます。
function getRandomColorHSL() {
const h = Math.floor(Math.random() * 360);
const s = Math.random();
const l = Math.random();
return hslToRgb(h, s, l);
}
このコードでは、hslToRgb()
関数を使ってHSI形式からRGB形式に変換しています。
Webライブラリを使用する
Chroma.js や Colr などのライブラリを使用すると、より高度なランダムカラー生成が可能になります。これらのライブラリは、特定の色相範囲の生成、類似色の生成、コントラストの高い色の生成など、様々な機能を提供しています。
// Chroma.js を使用してランダムな色を生成
const Color = require('chroma-js');
function getRandomColorChroma() {
return Color.random().hex();
}
画像からランダムな色を抽出する方法もあります。これは、特定の写真やアートワークの配色を再現したい場合などに役立ちます。
function getRandomColorFromImage(imageUrl) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 画像をロード
const image = new Image();
image.onload = function() {
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0);
// ランダムなピクセルを取得
const x = Math.floor(Math.random() * image.width);
const y = Math.floor(Math.random() * image.height);
const pixelData = ctx.getImageData(x, y, 1, 1).data;
// ピクセルの RGB 値を返す
const r = pixelData[0];
const g = pixelData[1];
const b = pixelData[2];
return `rgb(${r}, ${g}, ${b})`;
};
image.src = imageUrl;
}
シード値を使用してランダムな色を生成
シード値を使用すると、毎回同じランダムな色を生成することができます。これは、ゲーム開発やアニメーションなど、再現性を必要とする場面で役立ちます。
function getRandomColorWithSeed(seed) {
const r = Math.floor(Math.random() * 256) * seed;
const g = Math.floor(Math.random() * 256) * seed;
const b = Math.floor(Math.random() * 256) * seed;
return `rgb(${r}, ${g}, ${b})`;
}
このコードでは、seed
を Math.random()
関数の乗算子として使用しています。
特定の条件を満たすランダムな色を生成することもできます。例えば、ある閾値以上の明度を持つ色だけを生成したり、特定の色と類似した色だけを生成したりすることができます。
function getRandomColorWithCondition(condition) {
while (true) {
const color = getRandomColor(); // ランダムな色を生成
if (condition(color)) { // 条件を満たすかチェック
return color;
}
}
}
// 例:明度が 0.5 以上の色を生成
const isBrightEnough = function(color) {
const rgb = color.match(/\d+/g).map(Number);
const avg = (rgb[0] + rgb[1] + rgb[2]) / 3;
return avg >= 0.5;
};
const randomBrightColor = getRandomColorWithCondition(isBrightEnough);
console.log(randomBrightColor); // 例:#ffebcd
このコードでは、getRandomColorWithCondition()
関数を使って、条件を満たすランダムな色を生成しています。
これらの方法は、それぞれ異なる利
javascript random colors