View Full Version : inverse of hex value
11-11-2004, 04: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.
11-11-2004, 10:32 AM
How do I go about doing that? I'm not exactly a js guru, I only ever declare variables as var.
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
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
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?
I just realize that....By the way... Why not using RGB CSS from the begining, and save al lot of unecessary converting problems?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
var b = document.getElementsByTagName('body');
var bg = b.style.backgroundColor;
alert('the present background is '+b.style.backgroundColor)
alert('the present background will be change into inversed RGB color')
var oldCol = bg.split('(').split(')').split(',');
var newCol = new Array()
newCol[i] = 255-Number(oldCol[i]);
b.style.backgroundColor = 'rgb('+newCol+','+newCol+','+newCol+')';
alert('the new background is '+b.style.backgroundColor)
<body style="background-color: rgb(0,204,255)">
11-12-2004, 01:27 AM
Actually, I don't know why I didn't go that direction. I guess I didn't really think about it, I just said to myself- need to invert the color, just invert the binary representation, that's easy enough. I mean, converting base to base is not exactly complex.
Thanks very much for your help (and I actually figured out the string bit) .. :thumbsup:
Powered by vBulletin® Version 4.2.2 Copyright © 2016 vBulletin Solutions, Inc. All rights reserved.