hexと透過色 |
hexと透過色の計算について |
function hexToAlpha(hex) {
// 先頭の # を除去
hex = hex.replace(/^#/, '');
// RGBだけの場合(#RRGGBB)はアルファ値なし
if (hex.length === 6) {
return 1; // 不透明
}
if (hex.length === 8) {
// 最後の2桁がアルファ値
const alphaHex = hex.slice(6, 8);
const alphaDecimal = parseInt(alphaHex, 16); // 0〜255
return alphaDecimal / 255; // 0〜1 に変換
}
throw new Error('HEXコードの形式が不正です');
}
// 使用例
console.log(hexToAlpha('#FF0000FF')); // 1
console.log(hexToAlpha('#FF000080')); // 0.5019607843137255
function hexToAlpha(hex) {
// Remove the leading #
hex = hex.replace(/^#/, '');
// If there is only RGB (#RRGGBB), there is no alpha value.
if (hex.length === 6) {
return 1; // opaque
}
if (hex.length === 8) {
// The last two digits are the alpha value
const alphaHex = hex.slice(6, 8);
const alphaDecimal = parseInt(alphaHex, 16); // 0〜255
return alphaDecimal / 255; // Convert to 0 to 1
}
throw new Error('The HEX code format is invalid');
}
// Usage example
console.log(hexToAlpha('#FF0000FF')); // 1
console.log(hexToAlpha('#FF000080')); // 0.5019607843137255
const alpha = hexToAlpha('#FF000080');
console.log(Math.round(alpha * 100) + '%'); // "50%"