js中hexToRgba和rgbaToHex的方法

function rgbaToHex(rgba) {
  const rgbaValues = rgba.match(/\d+/g);
  const r = parseInt(rgbaValues[0]);
  const g = parseInt(rgbaValues[1]);
  const b = parseInt(rgbaValues[2]);
  const a = parseFloat(rgbaValues[3]);

  const hexR = r.toString(16).padStart(2, '0');
  const hexG = g.toString(16).padStart(2, '0');
  const hexB = b.toString(16).padStart(2, '0');
  const hexA = Math.round(a * 255).toString(16).padStart(2, '0');

  return `#${hexR}${hexG}${hexB}${hexA}`;
}

// const rgbaColor = 'rgba(255, 0, 0, 0.5)';
// const hexColor = rgbaToHex(rgbaColor);
function hexToRgba(hex, opacity) {
  var RGBA = "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," + parseInt( "0x" + hex.slice(5, 7)) + "," + opacity + ")";
  return {
      red: parseInt("0x" + hex.slice(1, 3)),
      green: parseInt("0x" + hex.slice(3, 5)),
      blue: parseInt("0x" + hex.slice(5, 7)),
      rgba: RGBA
  }
}

你可能感兴趣的:(javascript,前端,开发语言)