javascript - 检查渐变是否太轻javascript
问题描述
我正在尝试为每个页面的每个元素添加渐变,现在,我已经实现了它,但我遇到了问题。
如果渐变太亮,我的文字不可见,有没有办法检查渐变颜色是否太亮,然后将文字更改为黑色?
这是我的代码
这是渐变元素 = https://github.com/ghosh/uiGradients/blob/master/gradients.json
const cards = document.querySelectorAll('.card');
cards.forEach((card)=>{
let i = Math.floor(Math.random() * gradients.length);
const color = gradients[i].colors;
color.forEach((color)=> {
let finalGradient = `background: linear-gradient(to right, ${color}, ${color}, ${color}) !important;`;
card.style.cssText = finalGradient;
})
})
解决方案
这是我用来检测颜色是浅色还是深色的函数。您可以使用它并适应您的代码:
function isLightOrDark(color) {
// Variables for red, green, blue values
var r, g, b, hsp;
// Check the format of the color, HEX or RGB?
if (color.match(/^rgb/)) {
// If HEX --> store the red, green, blue values in separate variables
color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
r = color[1];
g = color[2];
b = color[3];
}
else {
// If RGB --> Convert it to HEX: http://gist.github.com/983661
color = +("0x" + color.slice(1).replace(
color.length < 5 && /./g, '$&$&'));
r = color >> 16;
g = color >> 8 & 255;
b = color & 255;
}
// HSP (Highly Sensitive Poo) equation from http://alienryderflex.com/hsp.html
hsp = Math.sqrt(
0.299 * (r * r) +
0.587 * (g * g) +
0.114 * (b * b)
);
// Using the HSP value, determine whether the color is light or dark
if (hsp>127.5) {
return 'light';
}
else {
return 'dark';
}
}
推荐阅读
- intellij-idea - 如何向 WebStorm/IntelliJ(使用 Angular)中的所有元素永久添加(touchStart)之类的事件
- azure - Azure Batch 在池上安装 blob 存储导致错误“无法安装包”
- charts - 我想在 GEE 中生成 NDVI 时间序列图表,但遇到错误“生成图表时出错:超出用户内存限制”。
- android - 在 Activity_main 中出现另一个窗口而不是主窗口
- java - 如何在代码运行的同一位置创建目录?
- regex - 如何检测给定字符串中的停用词并仅将该停用词从句子大小写或大写转换为小写
- asp.net - 如何在 Web Api 2 中实现 Oauth Refresh Token
- php - Guzzel 异常 - 500 内部服务器错误
- .net - 将 .Net Framework 类库添加到 .Net 核心控制台应用程序是否是个好主意
- maven - 在 azure pipeline mule 4 中无法执行 maven 的目标