如何从另一种颜色中减去一种颜色

How to subtract a color from another

本文关键字:颜色 一种 另一种      更新时间:2023-09-26

是否可以从另一种颜色中减去一种颜色?

示例(如果我错了,请纠正我)

如果我从白色中减去红色绿色,我期望结果为蓝色

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

[更新]

多亏了Rocket的回答,我需要一个function()来将我的结果转换成实际的颜色。

这是最后一个工作示例:

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"

您的white-red运行良好,只是JavaScript将值表示为基本值10。你需要将它们转换回16进制。看看这个答案,将值转换回十六进制。

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

我只是假设您使用的是RGB,因为还有很多其他混合颜色的方法。你必须把一种颜色分成3个不同的部分,R G和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] ;

要减去颜色,你必须减去颜色的每个组成部分,也许稍后将其转换回十六进制

*您可能希望稍后在上添加Alpha