Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract a color from another

Is it possible to subtract a color from another one ?

Example (correct me if i'm wrong):

If i subtract red and green from white, i am expecting the result to be blue.

var white = 0xFFFFFF,
    red = 0xFF0000,
    result = white - red;
console.log(result); //65535 <-- what is that ? can it be converted to 0x00FFFF ?

[update]

Thanks to Rocket's answer, it turned out i needed a function() to convert my results into an actual color.

Here is the final working example:

var toColor = function ( d ) {
       var c = Number(d).toString(16);
       return "#" + ( "000000".substr( 0, 6 - c.length ) + c.toUpperCase() );
    },
    white = 0xFFFFFF,
    red = 0xFF0000,
    green = 0x00FF00,
    result = toColor( white - red - green );

console.log( result ); // logs the expected result: "#0000FF"
like image 331
Pierre Avatar asked Jan 25 '12 16:01

Pierre


2 Answers

Your white-red works fine, it's just that JavaScript represents the values as base 10 values. You need to convert them back to base 16 (hex). Check out this answer, to convert the value back to hex.

var white = 0xFFFFFF, // Stored as 16777215
    red = 0xFF0000, // Stored as 16711680
    result = white - red; // 16777215 - 16711680 = 65535
console.log(result); // It's stored as base 10, so it prints 65535
var resultHex = result.toString(16); // 'ffff', converted back to hex
like image 112
Rocket Hazmat Avatar answered Oct 17 '22 14:10

Rocket Hazmat


I'm just assuming you are using RGB, because there are plenty of other ways to mix colors. You have to represent a color into 3* different parts, R G and B.

//            R  G  B 
var white = [ 1, 1, 1]; 
var red =   [ 0, 0, 0 ];
var result = [ white[0] - red[0], white[1] - red[1], white[2] - red[2] ;

To substract the color you have to substract each component of the color, and perhaps convert it back to hex later on.

* You might want to add Alpha later on

like image 6
TJHeuvel Avatar answered Oct 17 '22 14:10

TJHeuvel