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})`);
}

你可能感兴趣的:(javascript,前端,颜色值,背景,透明度,rgba)