RGB To Hex Conversion - make sure numbers 0 - 255

时间:2016-03-13 18:49:39

标签: javascript hex rgb

RGB to Hex conversion. My code below converts rgb to hex. There is one problem, r, g or b must be between 0 & 255. At present, if they are below 0, my code does not round them up to 0. I don't know why? Also I need to make sure the max is 255. Any advice please?

function rgb(r, g, b){
var newarr = [];
newarr.push(r, g, b );

var b = newarr.map(function(x){             
 if (isNaN(x) === true ) {
  if ( x  > 0 ) {
  parseInt(x).toString(16); 
  return  (x.length==1) ? "0"+x : x;  
  } else {
  x =  0 ;
  parseInt(x).toString(16); 
  return  (x.length==1) ? "0"+x : x; 
    }
    } else {
    parseInt(x).toString(16); 
  return  (x.length==1) ? "0"+x : x; 
  }

});


var tos = String(b) ;
var fin = tos.replace(/,/g," ");
fint = fin.replace(/\s/g,'');
document.write(fint);
}

rgb('0','0','-14');

This example currently returns: 0000-14

1 个答案:

答案 0 :(得分:3)

您的代码可能更简单:

function rgb(r, g, b){
    return [r, g, b].map(function(v) {
        return ('0' + 
            Math.min(Math.max(parseInt(v), 0), 255)
            .toString(16)
        ).slice(-2);
    }).join('');
}