What would be the preferred way to convert opacity (0 - 1) to hex (00 - ff) in Javascript?
My thoughts are to use an if statement to check if opacity is between 1 and 0.95 then use ff. Work my way down to 0.
What would be the preferred way to convert opacity (0 - 1) to hex (00 - ff) in Javascript?
My thoughts are to use an if statement to check if opacity is between 1 and 0.95 then use ff. Work my way down to 0.
At the most basic level, you're just converting a decimal to hex: How to convert decimal to hex in JavaScript?:
yourNum = yourNum.toString(16);
The 0.0 - 1.0 range is just a percentage format of the 0-255 range. So multiply your value (e.g. 0.5 * 255) then convert to hex, you'll get the correct value.
Based on the suggestions of the other answers:
Math.floor(0.0 * 255).toString(16); // Returns '00'
Math.floor(0.5 * 255).toString(16); // Returns '75'
Math.floor(1.0 * 255).toString(16); // Returns 'FF'
function applyOpacity(color, opacity) {
if (typeof color !== 'string' || color.length !== 7) return color;
if (opacity < 0) opacity = 0;
else if (opacity > 100) opacity = 100;
opacity = Math.round(opacity * 2.55);
return color + opacity.toString(16).toUpperCase().padStart(2, '0');
}
Math.floor()
This is the simple function to play hex colour code opacity.
const colour (colour, value) => {
const opacity = Math.floor(0.1 * value * 255).toString(16);
return colour + opacity;
};
colour (#172B4D, 5)
Create an util function like
const convertTotHex = (num) => {
const hex = Math.round(((num/100)*255)).toString(16);
return hex.length > 1 ? hex : 0+hex;
}