HTML上で16進数からRGB、CMYK、HSBの値を表示します。
以前作成したもののアップデート版です。
<!-- index.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>16進数カラーのRGB・CMYK・HSB表示</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #222;
color: white;
padding: 20px;
}
.color-box {
width: 150px;
height: 150px;
margin: 20px auto;
border-radius: 10px;
border: 2px solid white;
}
input {
width: 100px;
text-align: center;
font-size: 16px;
margin: 10px;
}
.result {
margin-top: 20px;
font-size: 18px;
}
</style>
</head>
<body>
<h2>16進数カラーのRGB・CMYK・HSB変換</h2>
<label>カラーコード(#RRGGBB):</label>
<input type="text" id="hexInput" value="#ff69b4">
<button onclick="convertColor()">変換</button>
<div class="color-box" id="colorBox"></div>
<div class="result">
<p><strong>RGB:</strong> <span
id="rgbValue"></span></p>
<p><strong>CMYK:</strong> <span
id="cmykValue"></span></p>
<p><strong>HSB:</strong> <span
id="hsbValue"></span></p>
</div>
<script>
function hexToRGB(hex) {
hex = hex.replace(/^#/, '');
if (hex.length === 3) {
hex = hex.split('').map(x => x + x).join('');
}
let r = parseInt(hex.substring(0, 2), 16);
let g = parseInt(hex.substring(2, 4), 16);
let b = parseInt(hex.substring(4, 6), 16);
return [r, g, b];
}
function rgbToCMYK(r, g, b) {
let c = 1 - (r / 255);
let m = 1 - (g / 255);
let y = 1 - (b / 255);
let k = Math.min(c, m, y);
if (k === 1) {
return [0, 0, 0, 100];
}
c = ((c - k) / (1 - k)) * 100;
m = ((m - k) / (1 - k)) * 100;
y = ((y - k) / (1 - k)) * 100;
k = k * 100;
return [Math.round(c), Math.round(m),
Math.round(y), Math.round(k)];
}
function rgbToHSB(r, g, b) {
let max = Math.max(r, g, b), min = Math.min(r, g, b);
let h, s, v = max;
let d = max - min;
s = max === 0 ? 0 : d / max;
if (max === min) {
h = 0;
} else {
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return [Math.round(h * 360), Math.round(s * 100),
Math.round(v / 255 * 100)];
}
function convertColor() {
let hex = document.getElementById("hexInput").value.trim();
if (!/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(hex)) {
alert("正しい16進数カラーコードを入力してください
(例: #ff69b4)。");
return;
}
let [r, g, b] = hexToRGB(hex);
let [c, m, y, k] = rgbToCMYK(r, g, b);
let [h, s, v] = rgbToHSB(r, g, b);
document.getElementById("colorBox").
style.backgroundColor = hex;
document.getElementById("rgbValue").
textContent = `(${r}, ${g}, ${b})`;
document.getElementById("cmykValue").
textContent = `(${c}%, ${m}%, ${y}%, ${k}%)`;
document.getElementById("hsbValue").
textContent = `(${h}°, ${s}%, ${v}%)`;
}
window.onload = convertColor;
</script>
</body>
</html>
<!-- index.html -->
表示するとデフォルトの hotpink(#ff69b4)が表示されます。確認したい色の16進巣を入力し[変換]をクリックすれば・・・
結果が表示されます。