zoukankan      html  css  js  c++  java
  • rgab 和hex颜色转化

    hex转rgb

    function hexToRgb (hex) {
      var shorthandRegex = /^#?([a-fd])([a-fd])([a-fd])$/i;
      hex = hex.replace(shorthandRegex, function (m, r, g, b) {
        return r + r + g + g + b + b;
      });
    
      var result = /^#?([a-fd]{2})([a-fd]{2})([a-fd]{2})$/i.exec(hex);
      return result ? 'rgb(' + [
        parseInt(result[1], 16),
        parseInt(result[2], 16),
        parseInt(result[3], 16)
      ].join(',') + ')' : hex;
    }
     
    console.log(hexToRgb('#C0F'));    // Output: rgb(204,0,255)
    console.log(hexToRgb('#CC00FF')); // Output: rgb(204,0,255)
    

    hex转rgba

    function hexToRgba (hex, opacity) {
      var shorthandRegex = /^#?([a-fd])([a-fd])([a-fd])$/i;
      hex = hex.replace(shorthandRegex, function (m, r, g, b) {
        return r + r + g + g + b + b;
      });
    
      var result = /^#?([a-fd]{2})([a-fd]{2})([a-fd]{2})$/i.exec(hex);
      opacity = opacity >= 0 && opacity <= 1 ? Number(opacity) : 1;
      return result ? 'rgba(' + [
        parseInt(result[1], 16),
        parseInt(result[2], 16),
        parseInt(result[3], 16),
        opacity
      ].join(',') + ')' : hex;
    }
     
    console.log(hexToRgba('#C0F'));         // Output: rgb(204,0,255,1)
    console.log(hexToRgba('#CC00FF', 0.3)); // Output: rgb(204,0,255,0.3)
    

    rgb转hex

    unction rgbToHex (rgb) {
      var bg = rgb.match(/^rgb((d+),s*(d+),s*(d+))$/);
      function hex (x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
      }
      return ("#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3])).toUpperCase();
    }
     
    console.log(rgbToHex('rgb(204,0,255)')); // Output: #CC00FF
    

    rgba转hex

    function hexify(color) {
      var values = color
        .replace(/rgba?(/, '')
        .replace(/)/, '')
        .replace(/[s+]/g, '')
        .split(',');
      var a = parseFloat(values[3] || 1),
          r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
          g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
          b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255);
      return "#" +
        ("0" + r.toString(16)).slice(-2) +
        ("0" + g.toString(16)).slice(-2) +
        ("0" + b.toString(16)).slice(-2);
    }
     
    var myHex = hexify('rgba(255,232,186,0.4)'); // "#f5faf3"
    
  • 相关阅读:
    ListIterator
    List与set
    iterator取集合元素
    我眼中的AI
    集合的共性方法
    集合转数组
    打开与关闭eclipse的自动补全功能
    Mr_matcher的细节1
    nodelet的应用
    nodelet的理解
  • 原文地址:https://www.cnblogs.com/miaSlady/p/13924729.html
Copyright © 2011-2022 走看看