SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Dec 2007
    Posts
    18
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    convert a value rgb(n,n,n) into HexaDecimal

    How to convert a value rgb(255,255,255) into #FFFFFF or vice versa in JavaScript.

    Please help me on this.

    Thanks & Regards
    Adil.

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    If you're going to use it for a style value, no conversion is necessary as css styles accept both formats
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The following script will convert to and from these formats:
    • red
    • rgb(255,0,0)
    • rgb(100%,0,0)
    • #f00
    • #ff0000


    HTML Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
    <html lang="en">
    <!--
     html and javascript test code; 
     use where supported
    -->
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
    <title>Color values</title>
    
    <style type="text/css" media="screen">
    body{font-size:125%;font-weight:500;background:white;color:black}
    table{border:3px ridge black;font-size:1.2em}
    td,th{border:1px black solid;text-align:center;color:black;background:none white}
    button{cursor:pointer;font-size:1.2em;color:black;margin-left:1em}
    button:hover{color:red}
    label{font-size:1.2em;padding:1ex 1em;border:1px solid black;background:none white;color:black}
    input{font-size:1em}
    </style>
    
    <script type="text/javascript">
    function check_colorman(obj){
    	if(typeof Run== 'undefined') Run= {};
    	
    	Run.brightDiff= function(bg,c,boo){
    		try{
    			bg= bg.toRgb();
    			c= c.toRgb();
    		}
    		catch(er){
    			bg= bg|| 'rgb(255,255,255)';
    			c= c|| 'rgb(0,0,0)';
    		}
    		var rX= /(\d+),(\d+),(\d+)/;
    		var BG= bg.match(rX);
    		var FG= c.match(rX);
    		var B1= (BG[1]*299 + BG[2]*587 + BG[3]*114)/ 1000;
    		var F1= (FG[1]*299 + FG[2]*587 + FG[3]*114)/ 1000;
    		var bright= Math.round(Math.abs(B1-F1));
    		var diff= (Math.max(BG[1], FG[1]) - Math.min(BG[1], FG[1])) +
    		(Math.max(BG[2],FG[2]) - Math.min(BG[2],FG[2])) +
    		(Math.max(BG[3],FG[3]) - Math.min(BG[3],FG[3]));
    		if(boo=== true)return !!(bright>125 && diff >500);
    		return [bright,diff];
    	}
    	Run.colornames= {
    		aqua:'#00ffff',black:'#000000',blue:'#0000ff',
    		fuchsia:'#ff00ff',gray:'#808080',green:'#008000',lime:'#00ff00',
    		maroon:'#800000',navy:'#000080',olive:'#808000',purple:'#800080',
    		red:'#ff0000',silver:'#c0c0c0',teal:'#008080',white:'#ffffff',yellow:'#ffff00'
    	}
    	Run.randomColor=function(radx){
    		var str= 'rgb(', A=[];
    		for(var i= 0; i<3; i++){
    			if(radx== 'safe'){
    				var tem= Math.round(Math.random()*5);
    				A.push( (tem*20)+ '%');
    			}
    			else A.push(Math.round(Math.random()*255));
    		}
    		str+= A.join(',')+')';
    		return (radx== 'safe')? str.isRgb(): str;
    	}
    	var CP= {
    		bwFlip: function(a,b){
    			var x= this.toRgb();
    			if(!x)return '';
    			if(!a) a= 'rgb(255,255,255)';
    			if(!b) b= 'rgb(0,0,0)';
    			if(Run.brightDiff(x,b,true))return b;
    			if(Run.brightDiff(x,a,true))return a;
    			var bd= Run.brightDiff(x,b);
    			var cd= Run.brightDiff(x,a);
    			if((bd[0]*4+ bd[1]) > (cd[0]*4+ cd[1])) return b;
    			if((cd[0]*4+ cd[1]) > (bd[0]*4+ bd[1])) return a;
    			return (bd[0]< cd[0])? a: b;
    		},
    		colorSafe:function(){
    			var c= this.toRgb();
    			var str= c.replace(/(\d+)/g,function(w){
    				return (Math.round(parseInt(w,10)/51)*51);
    			});
    			return str;
    		},
    		getColorname: function(){
    			var c= this.toHexColor();
    			if(c){
    				var G= Run.colornames;
    				for(var p in G){
    					if(G[p]== c) return p;
    				}
    			}
    			return '';
    		},
    		isHexColor: function(){
    			var c= this.tlclean();
    			if(/^\#[a-f0-9]{3}$/.test(c)){
    				var i= 1, A= c.split('');
    				while(i<4) A[i]+= ''+A[i++];
    				return A.join('');
    			}
    			return (/^\#[a-f0-9]{6}$/.test(c))? c: false;
    		},
    		isRgb: function (){
    			var c= this.tlclean();
    			c= /^rgb\((\d{1,3}%?,){2}\d{1,3}%?\)$/.test(c) ? c : '';
    			if (/%/.test(c)){
    				c= c.replace(/(\d+%?)/g,function(w){
    					return Math.round(parseInt(w)*2.55)+'';
    				})
    			}
    			return c || false;
    		},
    		padZero: function(len,c){
    			c= c || '0';
    			var s= this;
    			while(s.length< len) s= c+s;
    			return s;
    		},
    		toHexColor: function(){
    			var c= this.tlclean();
    			var tem= Run.colornames[c] || c.isHexColor();
    			if(!tem){
    				c= c.isRgb();
    				if(c){
    					c= c.replace('rgb(','').replace(/\)$/,'');
    					tem= '#'+c.replace(/(\d+,?)/g,function(w){
    						return parseInt(w).toString(16).padZero(2);
    					})
    				}
    			}
    			return tem || '';
    		},
    		toRgb: function(){
    			var c= this.tlclean();
    			var tem= c.isRgb() || '';
    			if(!tem) {
    				var hex= c.toHexColor();
    				if(!hex) return '';
    				hex= hex.replace(/^#/,'0x');
    				tem= [(hex >>16) & 255,(hex >> 8) & 255, hex & 255];
    				return 'rgb('+tem.join(',')+')';
    			}
    			return tem || '';
    		},
    		tlclean: function(){
    			return this.toLowerCase().replace(/ +/g,'');
    		}
    	}
    	if(typeof obj!='object')obj=String.prototype;
    	for(var p in CP) obj[p]= CP[p];
    	return !!document.createTextNode;
    }
    
    // The rest of the code is a test application using the methods defined above
    
    
    function colorDemo(c){
    	var tem= c.tlclean();
    	c= c.toRgb();
    	if(!c) return;
    	var bc=c.bwFlip();
    	var who= Run.mr('colorTable');
    	var pa= document.addEl('tr');	
    	var B= 'toHexColor,getColorname,toRgb'.split(',');
    	var temp,j= B.length;
    	document.addEl('td',pa,tem,{textAlign:'right',paddingRight:'1ex',color:bc,background:c});
    	while(j){
    		temp= B[--j];
    		temp= String(eval('\"'+tem+'".'+ temp+'()'));
    		document.addEl('td',pa,temp);			
    	}
    	who.insertBefore(pa,who.firstChild);
    
    }
    
    onload= function(){
    	if(check_colorman()===false) return false;
    	Run.mr=function(hoo){
    		if(typeof hoo=='string') return document.getElementById(hoo);
    		if(hoo.nodeType==1) return hoo;
    		return false;
    	}
    	Run.demoColors= 'red;rgb(255,0,0);rgb(100%,0,0);#f00;#ff0000'.split(';');
    	if(document.createTextNode){
    		document.addEl= function(wot,pa,s,c){
    			var el= document.createElement(wot);
    			if(s) el.appendChild(document.createTextNode(s));
    			for(var p in c)el.style[p]= c[p];
    			if(pa) pa.appendChild(el);
    			return el;
    		}
    		var who= Run.mr('input_color');
    		who.onchange= function(e){
    			var who= Run.mr('input_color');
    			var c= who.value? who.value.toRgb(): '';
    			var pa= who.parentNode;
    			if(c){
    				pa.style.backgroundColor= c;
    				pa.style.color= c.bwFlip();
    				return colorDemo(who.value);				
    			}
    			else{
    				who.value= '';
    				pa.style.backgroundColor= '';
    				pa.style.color= '';
    				return false;
    			}
    		}
    		who.onkeypress= function(e){
    			e= window.event || e;
    			var el= e.srcElement || e.target;
    			if(e.keyCode== 13){	
    				el.blur();				
    			}
    		}
    		Run.mr('ranColorBtn').onclick= function(){
    			var who= Run.mr('input_color');
    			who.focus();
    			var diff= Math.round(Math.random()*8);
    			if(diff< 6 || Run.colorMemry== 'done'){
    				who.value= Run.randomColor();
    				if(diff< 3)who.value= who.value.toHexColor();
    			}
    			else{
    				var A= [];
    				if(!Run.colorMemry){
    					Run.colorMemry= {};
    					for(var p in Run.colornames){
    						Run.colorMemry[p]= Run.colornames[p];
    					}
    				}
    				for(var p in Run.colorMemry) A.push(p);
    				if(A.length== 1){
    					who.value= A[0];					
    					Run.colorMemry= 'done';					
    				}
    				else{
    					var n= Math.floor(Math.random()*A.length);
    					var tem= A[n];
    					if(tem){
    						who.value= tem;
    						delete Run.colorMemry[tem];
    					}
    				}
    			}
    			return who.onchange();
    		}
    	}
    }
    
    
    </script>
    </head>
    
    <body>
    <h1>Color Values</h2>
    <h2>Javascript string conversion</h2>
    <p style="max-width:700px">Colors on the web are expressed as string values, 
    either as a common color name, or as a triplet of values that signify the amounts of red, green and blue 
    in the color. All of these examples are valid ways to indicate the same color:</p>
    <ul>
    	<li>red</li>
    	<li>rgb(255,0,0)</li>
    	<li>rgb(100%,0,0)</li>
    	<li>#f00</li>
    	<li>#ff0000</li>
    </ul>
    <p>Type a color string and press the Enter key, or click the 'Random' button for a random color.</p>
    <p>
     <label> Color string:<input id="input_color" type="text" value="" size="24"></label>
    <button type="button" id="ranColorBtn">Random</button>
    </p>
    <table cellpadding="0" cellspacing="0" width="90%" summary="summary">
    <caption>Color Values</caption>
    <thead class="sortableClass">
    <tr><th width="30%" cols="1" >String</th><th width="30%">RGB</th>
    <th width="20%">Name</th><th width="20%">Hex</th></tr>
    </thead>
    <tbody id="colorTable">
    </tbody>
    </table>
    
    </body>
    </html>
    Last edited by mrhoo; Jan 19, 2008 at 23:31. Reason: changed randomColor method


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •