Skip to content

Instantly share code, notes, and snippets.

@MakStashkevich
Forked from danieliser/es5.js
Created January 29, 2023 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MakStashkevich/99d5ed9d7dbbe4af5268fe545585a6d8 to your computer and use it in GitHub Desktop.
Save MakStashkevich/99d5ed9d7dbbe4af5268fe545585a6d8 to your computer and use it in GitHub Desktop.
Convert Hex Color to rgba with opacity
/**
* ECMA2015
*/
function convertHex(hexCode, opacity = 1){
var hex = hexCode.replace('#', '');
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
var r = parseInt(hex.substring(0,2), 16),
g = parseInt(hex.substring(2,4), 16),
b = parseInt(hex.substring(4,6), 16);
/* Backward compatibility for whole number based opacity values. */
if (opacity > 1 && opacity <= 100) {
opacity = opacity / 100;
}
return 'rgba('+r+','+g+','+b+','+opacity+')';
}
/**
* ECMA2016 / ES6
*/
const convertHexToRGBA = (hexCode, opacity = 1) => {
let hex = hexCode.replace('#', '');
if (hex.length === 3) {
hex = `${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}`;
}
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
/* Backward compatibility for whole number based opacity values. */
if (opacity > 1 && opacity <= 100) {
opacity = opacity / 100;
}
return `rgba(${r},${g},${b},${opacity})`;
};
describe('convertHexToRGBA', () => {
test('accepts a hex value of 6 numbers and returns a rgba color string', () => {
expect(convertHexToRGBA('#F3F3F3')).toBe('rgba(243,243,243,1)')
})
test('accepts a hex value of 6 numbers with opacity of 1 and returns same color string', () => {
expect(convertHexToRGBA('#000', 1)).toBe(convertHexToRGBA('#000'))
})
test('accepts a hex value of 6 numbers with opacity and returns a rgba color string', () => {
expect(convertHexToRGBA('#000', 0.5)).toBe('rgba(0,0,0,0.5)')
})
test('accepts a hex value of 3 numbers and returns a rgba color string', () => {
expect(convertHexToRGBA('#aaa')).toBe('rgba(170,170,170,1)')
})
test('accepts a hex value of 3 numbers with opacity and returns a rgba color string', () => {
expect(convertHexToRGBA('#aaa', 0.5)).toBe('rgba(170,170,170,0.5)')
})
test('accepts a hex value of 3 numbers with opacity of 1 and returns same color string', () => {
expect(convertHexToRGBA('#aaa', 1)).toBe(convertHexToRGBA('#aaa', 1))
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment