本文介绍了如何从另一种颜色中减去一种颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to subtract a color from another one ?

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

如果我从白色中减去红色绿色,我期待结果是蓝色.

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

[更新]

感谢 Rocket 的回答,结果我需要一个 function() 来转换我的结果变成了实际的颜色.

[update]

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

这是最终的工作示例:

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 为基数的值.您需要将它们转换回 base 16(十六进制).查看这个答案,将值转换回十六进制.

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

这篇关于如何从另一种颜色中减去一种颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 19:53
查看更多