HTML上で指定色の明暗を10%きざみで表示させます。
<!-- index.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>色の明るさ・暗さ調整</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
text-align: center;
}
.color-box {
display: inline-block;
width: 100px;
height: 50px;
margin: 5px;
line-height: 45px;
text-align: center;
color: #000;
font-weight: bold;
border: 1px solid #000;
}
.color-row {
margin-bottom: 20px;
}
.color-row h2 {
margin: 10px 0;
}
</style>
</head>
<body>
<h2>指定色と明るい色・暗い色</h2>
<label for="colorInput">色を指定 (HEX): </label>
<input type="text" id="colorInput" value="#8a2be2">
<button onclick="displayColors()">色を生成</button>
<div id="colorsContainer">
<div class="color-row" id="originalColor">
</div>
<div class="color-row" id="lighterColors">
</div>
<div class="color-row" id="darkerColors">
</div>
</div>
<script>
function hexToRgb(hex) {
hex = hex.replace(/^#/, "");
if (hex.length === 3) {
hex = hex.split("").map(c => c + c).join("");
}
const r = parseInt(hex.slice(0, 2), 16);
const g = parseInt(hex.slice(2, 4), 16);
const b = parseInt(hex.slice(4, 6), 16);
return { r, g, b };
}
function rgbToHex(r, g, b) {
return (
"#" +
[r, g, b]
.map(x => Math.min(255, Math.max(0, Math.round(x))).
toString(16).padStart(2, "0"))
.join("")
);
}
function adjustColor(r, g, b, factor) {
return {
r: r + (255 - r) * factor,
g: g + (255 - g) * factor,
b: b + (255 - b) * factor
};
}
function darkenColor(r, g, b, factor) {
return {
r: r * (1 - factor),
g: g * (1 - factor),
b: b * (1 - factor)
};
}
function displayColors() {
const inputColor =
document.getElementById("colorInput").value;
const { r, g, b } = hexToRgb(inputColor);
const originalColorDiv =
document.getElementById("originalColor");
const lighterColorsDiv =
document.getElementById("lighterColors");
const darkerColorsDiv =
document.getElementById("darkerColors");
// 初期化
originalColorDiv.innerHTML = "";
lighterColorsDiv.innerHTML = "";
darkerColorsDiv.innerHTML = "";
// 指定色を表示
const originalHex = rgbToHex(r, g, b);
originalColorDiv.innerHTML += `
<br>
<div class="color-box"
style="background-color: ${originalHex};">
<br>${originalHex}</div>
`;
// 明るい色と暗い色を計算して表示
for (let i = 1; i <= 9; i++) {
const factor = i * 0.1;
// 明るい色
const lighter = adjustColor(r, g, b, factor);
const lighterHex = rgbToHex(lighter.r, lighter.g, lighter.b);
lighterColorsDiv.innerHTML += `
<div class="color-box"
style="background-color: ${lighterHex};">
<br>${lighterHex}</div>
`;
// 暗い色
const darker = darkenColor(r, g, b, factor);
const darkerHex = rgbToHex(darker.r, darker.g, darker.b);
darkerColorsDiv.innerHTML += `
<div class="color-box"
style="background-color: ${darkerHex};">
<br>${darkerHex}</div>
`;
}
}
</script>
</body>
</html>
<!-- index.html -->
実行直後の画面です。デフォルトの#8a2be2が入力されます。
<input type="text" id="colorInput" value="#8a2be2">
そのまま[色を生成]をクリックすると・・・