JS根据颜色值和透明度获取带透明度的背景

在设置背景的时候,有时需要先选颜色值,然后再调整透明度,但却又不能影响文字透明度(功能类似简单封面EasyCover (jiandan.link)),此时可以将颜色值(线性颜色或者十六进制颜色)和透明度作为参数,然后处理成rgba的格式。

function convertGradientsToRgba(gradients, opacity) {
  // 修改后的正则表达式以匹配多重渐变和多个色标
  const gradientRegex = /(linear-gradient\(([^,]+?)(?:,(?:\s*rgba?\([^)]+\)|\s*#(?:[0-9A-Fa-f]{3}){1,2})\s*(?:[0-9]{1,3}%?)?)*\))/g;
  let match;
  let outputGradient = [];

  // 匹配每个渐变,并分别处理
  while ((match = gradientRegex.exec(gradients)) !== null) {
    const gradientDeclaration = match[0];

    // 分离渐变类型和颜色并将每个颜色转换为rgba
    const colorsRegex = /(rgba?\([^)]+\)|#(?:[0-9A-Fa-f]{3}){1,2})\s*(?:[0-9]{1,3}%?)?/g;
    let colorMatch;
    let gradientColors = [];

    while ((colorMatch = colorsRegex.exec(gradientDeclaration)) !== null) {
      let color = colorMatch[0];
      if (!/^rgba/.test(color)) {
        // 只转换非rgba颜色
        color = convertHexToRgba(color, opacity);
      } else {
        // 更新存在的rgba颜色的透明度
        color = updateRgbaOpacity(color, opacity);
      }
      gradientColors.push(color);
    }

    // 用转换后的颜色值替换原有颜色
    const newGradient = gradientDeclaration.replace(colorsRegex, () => gradientColors.shift());
    outputGradient.push(newGradient);
  }

  // 将所有的渐变合并
  return outputGradient.join(', ');
}

function convertHexToRgba(hex, alpha) {
  if (!/#/.test(hex)) { 
    return hex; 
  }

  const hexColor = hex.trim().replace('#', '');
  const r = parseInt(hexColor.substring(0, 2), 16);
  const g = parseInt(hexColor.substring(2, 4), 16);
  const b = parseInt(hexColor.substring(4, 6), 16);

  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}

function updateRgbaOpacity(rgba, alpha) {
  return rgba.replace(/rgba?\(([^,]+), ([^,]+), ([^,]+),?[^)]*\)/, `rgba($1, $2, $3, ${alpha})`);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

QmagicianRX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值