gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 13:11:26 26 4
gpt4 key购买 nike

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

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

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 ?

[更新]

感谢Rocket's answer ,结果我需要一个 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(十六进制)。查看this answer , 将值转换回十六进制。

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

关于javascript - 如何从另一种颜色中减去一种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9005917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com