Using JavaScript, you can calculate the opacity percentage of an 8-digit hexadecimal color code in the following way:
- If non-8-digit color code, then return
100
(i.e. fully opaque); - If 8-digit color code, then extract the last two digits (i.e. alpha channel value) from it, and;
- Calculate the opacity (in percent) for the extracted last two digits of the 8-digit color code.
For example, you can implement this in the following way:
const calcHexOpacity = (hexValue) => { // 1: if not 8-digit color code, return `100` if (hexValue.length < 8) { return 100; } // 2: extract alpha channel value (last two digits) const alpha = parseInt(hexValue.substring(6, 8), 16); // 3: calculate opacity in percent const opacity = Math.round(alpha / 255 * 100); return Math.round(alpha / 255 * 100); }; console.log(calcHexOpacity('0000ff00')); // 0 // ... console.log(calcHexOpacity('0000ff40')); // 25 // ... console.log(calcHexOpacity('0000ff80')); // 50 // ... console.log(calcHexOpacity('0000ffbf')); // 75 // ... console.log(calcHexOpacity('0000ffff')); // 100
This code works as follows:
- The code first checks if the hexadecimal color code has 8 digits. If it does not, it means that there is no alpha channel value in the code and the opacity percentage is assumed to be
100%
. Therefore, the function returns100
. - If the color code has 8 digits, the alpha channel value is extracted from the last two digits of the code.
- To calculate the opacity percentage, the alpha channel value is first converted from an integer between
0
(fully transparent) and255
(fully opaque) to a decimal value between0
and1
by dividing it by255
. The resulting decimal value is then multiplied by100
to get the opacity percentage, which is represented as a number between0
and100
. - The opacity percentage is then rounded to the nearest integer using the
Math.round()
function to provide a whole number value for the opacity percentage.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.