我有一个 Javascript Canvas ,我想在鼠标悬停时用“突出显示”颜色填充一个矩形。我的矩形有一个动态颜色 DC,所以它可以是从白色到黑色的任何颜色,甚至可以是透明的颜色。我需要一种算法来为我提供从 DC 开始的这种“突出显示”颜色。
我想我必须在阈值 T 上测试亮度 L:
如果 L < T 增加DC的亮度 别的 降低DC的亮度
这是一个好方法吗?
我不确定如何处理白色和黑色。我应该只选择合适的颜色吗?
最佳答案
你可以这样使用:
检查这个例子:http://jsfiddle.net/bocanegra_carlos/8ej4r02f/
// Get a contrasting Hex color value for a given color
// @param {String} hexColor: Hexadecimal color value (i.e. "#FF0000")
// @param {String} conversionType: Conversion type [YIQ|Opposite|50%]
// @return {String}
function getHighlightColor (hexColor, conversionType) {
if (!isValidColor(hexColor)) return "#000000";
switch (conversionType){
case "yiq":
// YIQ (Based on luminosity)
// *****************
hexColor = hexColor.substr(1);
if (hexColor.length == 3) {
var r = parseInt(hexColor.substr(0,1) + hexColor.substr(0,1),16);
var g = parseInt(hexColor.substr(1,1) + hexColor.substr(1,1),16);
var b = parseInt(hexColor.substr(2,1) + hexColor.substr(2,1),16);
}
else {
var r = parseInt(hexColor.substr(0,2),16);
var g = parseInt(hexColor.substr(2,2),16);
var b = parseInt(hexColor.substr(4,2),16);
}
var yiq = ((r*299)+(g*587)+(b*114))/1000;
return (yiq >= 128) ? '#000000' : '#FFFFFF';
break;
case "opposite":
// Opposite Color
// *****************
hexColor = hexColor.substring(1);
colorLength = hexColor.length;
hexColor = parseInt(hexColor, 16);
hexColor = 0xFFFFFF ^ hexColor;
hexColor = hexColor.toString(16);
if (colorLength == 6)
hexColor = ("000000" + hexColor).slice(-6);
else if (colorLength == 3)
hexColor = ("000" + hexColor).slice(-3);
else
hexColor = "000000";
return "#" + hexColor;
break;
case "50%":
// 50% (Black / White)
// *****************
hexColor = hexColor.substring(1)
if (hexColor.length == 4)
hexColor =
hexColor.substr(0,1) + hexColor.substr(0,1) +
hexColor.substr(1,1) + hexColor.substr(1,1) +
hexColor.substr(2,1) + hexColor.substr(2,1);
return (parseInt(hexColor, 16) > (0xffffff/2)) ? '#000000':'#FFFFFF';
}
}
// Validate the input value is a valid Hex color (i.e. Valid colors "#FF3400" or "#A9F". Invalid Colors "ASD102", "gray")
// @param {String} value: Value to test
// @return {Boolean}
function isValidColor(value){
var hexColorRegExp = new RegExp(/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i);
return hexColorRegExp.test(value);
}
关于javascript - 从指定颜色中获取高亮颜色的合适算法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32141723/