HTML上で16進数の色に該当するRGBとCMYKの色の値を表示
<!-- 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とCMY値</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 20px;
}
.color-box {
width: 120px;
height: 120px;
margin: 20px auto;
border: 2px solid #000;
border-radius: 10px;
}
.info {
font-size: 16px;
margin-top: 10px;
}
#output {
margin-top: 20px;
}
</style>
</head>
<body>
<h2>16進数のRGBとCMY値</h2>
<p>16進数の色コードを入力してください(例: #ff69b4):</p>
<input type="text" id="hexInput" placeholder="#000000">
<button onclick="updateColor()">色を表示</button>
<div id="output">
<div class="color-box" id="colorBox"></div>
<div class="info" id="rgbInfo"></div>
<div class="info" id="cmykInfo"></div>
</div>
<script>
// hexToRgb() 関数で、16進数の色コードをRGB形式に変換
function hexToRgb(hex) {
const bigint = parseInt(hex.slice(1), 16);
const r = (bigint >> 16) & 255;
const g = (bigint >> 8) & 255;
const b = bigint & 255;
return { r, g, b };
}
// rgbToCmyk() 関数で、RGB値をCMYK形式に変換
function rgbToCmyk(r, g, b) {
const c = 1 - (r / 255);
const m = 1 - (g / 255);
const y = 1 - (b / 255);
const k = Math.min(c, m, y);
const cmyk = {
c: ((c - k) / (1 - k) * 100).toFixed(1),
m: ((m - k) / (1 - k) * 100).toFixed(1),
y: ((y - k) / (1 - k) * 100).toFixed(1),
k: (k * 100).toFixed(1),
};
return cmyk;
}
function updateColor() {
const hex = document.getElementById("hexInput").value;
if (!/^#([0-9A-Fa-f]{6})$/.test(hex)) {
alert("正しい16進数の色コードを入力してください
(例: #ff5733)");
return;
}
// 16進数からRGBに変換
const { r, g, b } = hexToRgb(hex);
// RGBからCMYKに変換
const { c, m, y, k } = rgbToCmyk(r, g, b);
// 色ボックスの背景色を更新
const colorBox = document.getElementById("colorBox");
colorBox.style.backgroundColor = hex;
// RGB情報を表示
const rgbInfo = document.getElementById("rgbInfo");
rgbInfo.textContent = `RGB: (${r}, ${g}, ${b})`;
// CMYK情報を表示
const cmykInfo = document.getElementById("cmykInfo");
cmykInfo.textContent =
`CMYK: (${c}%, ${m}%, ${y}%, ${k}%)`;
}
</script>
</body>
</html>
<!-- index.html -->
実行したら16進数を入力し[色を表示]をクリックするだけです。
直ぐに結果が表示されます。