戻る

hexと透過色
hexと透過色の計算について

不透明な赤色を表すと下記のようになります。
[HEX]
#FF0000FF
[RGB]
rgb(255 0 0 / 1.00)
この赤色を透過色50%で表すと下記のようになります。
[HEX]
#FF000080
[RGB]
rgb(255 0 0 / 0.50)
この計算式には下記の計算をすると結果が得られました。
[下記プログラムの中から一部抜粋]
// a: 0~1 を 0~255 に変換
const aa = Math.round(a * 255);

この計算をみると
透過色50%の場合
aは50%に相当するので
aaの値は
0.5 * 255 = 127.5なので四捨五入をして
128になります、
toHex関数の引数に128をを設定することで16進数の80に変換してくれます。
これにより透過色50%の赤色はhexで表現すると
#FF000080
になります。

HEXの最後の2桁がアルファ値(0〜255)であることから
255で割ると、0〜1の透過率を得られます。

copy
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
copy
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
[ポイント]
parseInt(文字列, 16)で16進数を10進数に変換します。
0〜255の値を255で割ると 0〜1 の透過率になります。
50%の場合は128 / 255 ≒ 0.502となり、ほぼ0.5となります。

もし「ちょうど50%かどうか」を判定したい場合は、
小数点の誤差を考慮して四捨五入するといいでしょう。
const alpha = hexToAlpha('#FF000080');
console.log(Math.round(alpha * 100) + '%'); // "50%"



戻る