반응형
//rgba validation check
function validRGBA(rgba) {
if(!rgba instanceof Array){
return false;
}
else if(rgba.length<3){
return false;
}
//red value validation check
else if(!(reba[0]&&reba[0]>=0 && reba[0]<=255)){
return false;
}
//green value validation check
else if(!(reba[1]&&reba[1]>=0 && reba[1]<=255)){
return false;
}
//blue value validation check
else if(!(reba[2]&&reba[2]>=0 && reba[2]<=255)){
return false;
}
//alpha value validation check
if(reba[3]&&!(&&reba[3]>=0 && reba[3]<=1)){
return false;
}
return true;
}
//RGBA → HEX
function RGBA2HEX(rgba) {
if(!validRGBA(rgba)){
throw new Error(`'${rgba}'is not rgba format!`);
}
let hex = '';
rgba.slice(0, 3).forEach((c, index) => {
hex +=
parseInt(c).toString(16).length != 1
? parseInt(c).toString(16)
: '0' + parseInt(c).toString(16);
});
//alpha value change
if (rgba[3]) {
hex += parseInt(`${255*rgba[3]}`).toString(16);
}
return `#${hex.toUpperCase()}`;
}
//hex validation check
function validHEX(hex) {
if(typeof hex !=='string'){
return false;
}
var reg = new RegExp(/^\#?[0-9a-fA-F]{6,8}$/);
return reg.test(hex);
}
//HEX → RGBA
function HEX2RGBA(hex){
if(!validHEX(hex)){
throw new Error(`'${hex}' is not valid hex format!`);
}
let temp = hex.replace("#","");
let len = temp.length/2;
let rgba = [];
for(let i=0; i<len; i++){
let hTarget = temp.substring(i*2,(i+1)*2);
//alpha value(0~1)
if(i===3){
rgba.push(parseInt(hTarget,16)/255);
}
else{//r,g,b value (0~255)
rgba.push(parseInt(hTarget,16));
}
}
return rgba;
}
반응형
'개발 > javascript' 카테고리의 다른 글
[javascript] 원시타입과 객체 Boolean으로 변환 (0) | 2023.01.01 |
---|---|
ECMAScript 2015(ES6) (0) | 2022.12.30 |
[npm] 패키지 관리 (2) | 2022.12.23 |
[javascript] javascript란? #정의 #역사 (0) | 2019.02.02 |
[javascript] ModalDialog에서 window.open시 session 끊기는 문제 (0) | 2019.01.23 |