为了账号安全,请及时绑定邮箱和手机立即绑定

输入的颜色如何计算背景颜色?

输入的颜色如何计算背景颜色?

慕桂英546537 2022-05-14 14:33:36
在我的@vue/cli 4.1.1 应用程序中,用户输入颜色,我必须用输入的颜色输出颜色值,我想知道如何计算和设置背景颜色以确保输入的颜色值清晰可见。我的意思是如果用户输入白色(或接近)背景必须是黑暗的?
查看完整描述

2 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

你可以给一个反转颜色 -255-color对于每个rgb


function bg(r, g, b) {return [255-r, 255-g, 255-b]}

如果您以十六进制格式获取它,则可以将其转换为rgb,然后获取反转。像这样:


function invert(hex){

  hex = parseInt(hex.substring(1), 16);

  var r = hex >> 16;

  hex -= r << 16;

  var g = hex >> 8;

  hex -= g << 8;

  var b = hex;

  return `rgb(${255-r},${255-g},${255-b})`;

}

var color1 = "#eeff00";

var color2 = "#22faef";

var color3 = "#f1f1f1";

document.querySelector('#a').style = `color:${color1};background-color:${invert(color1)}`;

document.querySelector('#b').style = `color:${color2};background-color:${invert(color2)}`;

document.querySelector('#c').style = `color:${color3};background-color:${invert(color3)}`;

div {

padding: 10px;

}

<div id="a">Hello world!</div>

<div id="b">Hello world!</div>

<div id="c">Hello world!</div>


查看完整回答
反对 回复 2022-05-14
?
眼眸繁星

TA贡献1873条经验 获得超9个赞

您可以根据亮度确定输入的颜色是浅色还是深色。


在这里你可以找到一个计算它的公式。


因此,例如,您可以isLight像这样定义函数


function isLight(color) {

  // Converting hex color to rgb

  const [red, green, blue] = hexToRgb(color);


  // Determine luminance

  const luminance = (0.299 * red + 0.587 * green + 0.114 * blue)/255;


  // Returning true if color is light

  return luminance > 0.5;

}


// function for converting hex colors to rgb array format

function hexToRgb(hex) {

  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);

  return result ? [

    parseInt(result[1], 16),

    parseInt(result[2], 16),

    parseInt(result[3], 16)

  ] : null;

}

通过使用此功能,您可以确定用户颜色是浅色还是深色,从而设置适当的背景


查看完整回答
反对 回复 2022-05-14
  • 2 回答
  • 0 关注
  • 187 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号