PDA

View Full Version : inverse of hex value

Mhtml
11-11-2004, 05:47 AM
I have created a spreadsheet system using js/php. The user has the ability to change the background color of a cell. Now I wish for the text color in the cell to be the inverse of the hex value which is set as the background.

Currently I just convert the hex to bin, flip the bits and then go back to hex. But if the value is 000000 or 0* or *0 I lose the 0s. I was thinking perhaps I could pad the value with a 1 at either end and remove it later, unless there is a way to stop js trimming off these values.

Kor
11-11-2004, 11:20 AM
Try modify your script to return strings instead of numbers when converting back in hexa. Anyway you will use the hexa result as a string in your javascript code.

Mhtml
11-11-2004, 11:32 AM
How do I go about doing that? I'm not exactly a js guru, I only ever declare variables as var.

Kor
11-11-2004, 12:04 PM
well... firts at all I don't think you put the problem in an appropiate manner. The "opposite" color, as you said must be treated, I guess, in a RGB manner, which means you don't need to converty bunary, but decimal.

Assuming that you have the hexa color

#00CCFF
that means you must split that in 3 and convert to decimal

00 Hex = 0; Red
CC Hex = 204; Green
FF Hex = 255; Blue

parseInt(hex,16) will do that job

Now the "opposite" color could be the difference between 255 and the correspondend RGB value

255-0 = 255 = FF Hex ; Red
255-204 = 51 = 33 Hex; Green
255-255 = 0 = 00 Hex; Blue

to convert in hexa you need a function

In fact you don't need to convert it back to hexa, but use them as well in you CSS on-the-fly code

object.style.color='rgb(255,51,0)';

That means
#FF3300

In conclusion I think you must split in 3, convert each in decimal, substract each from 255, and if you want hexa by all means, convert each back in hexa, reasamble and adding # to the result string. It would not be very difficult, can you manage it by yourself?

Kor
11-11-2004, 12:14 PM
I just realize that....By the way... Why not using RGB CSS from the begining, and save al lot of unecessary converting problems?

Kor
11-11-2004, 12:42 PM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script language="JavaScript" type="text/JavaScript">
function bla(){
var b = document.getElementsByTagName('body')[0];
var bg = b.style.backgroundColor;
alert('the present background will be change into inversed RGB color')
var oldCol = bg.split('(')[1].split(')')[0].split(',');
var newCol = new Array()
for(var i=0;i<oldCol.length;i++){
newCol[i] = 255-Number(oldCol[i]);
}
b.style.backgroundColor = 'rgb('+newCol[0]+','+newCol[1]+','+newCol[2]+')';
}