color.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const colorChange={
  2. rgbToHex: function (val) { //RGB(A)颜色转换为HEX十六进制的颜色值
  3. var r, g, b, a,
  4. regRgba = /rgba?\((\d{1,3}),(\d{1,3}),(\d{1,3})(,([.\d]+))?\)/, //判断rgb颜色值格式的正则表达式,如rgba(255,20,10,.54)
  5. rsa = val.replace(/\s+/g, '').match(regRgba);
  6. if (!!rsa) {
  7. r = parseInt(rsa[1]).toString(16);
  8. r = r.length == 1 ? '0' + r : r;
  9. g = (+rsa[2]).toString(16);
  10. g = g.length == 1 ? '0' + g : g;
  11. b = (+rsa[3]).toString(16);
  12. b = b.length == 1 ? '0' + b : b;
  13. a = (+(rsa[5] ? rsa[5] : 1)) * 100;
  14. return { hex: '#' + r + g + b, r: parseInt(r, 16), g: parseInt(g, 16), b: parseInt(b, 16), alpha: Math.ceil(a) };
  15. } else {
  16. return { hex: '无效', alpha: 100 };
  17. }
  18. },
  19. hexToRgb: function (val) { //HEX十六进制颜色值转换为RGB(A)颜色值
  20. // 16进制颜色值的正则
  21. var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  22. // 把颜色值变成小写
  23. var color = val.toLowerCase();
  24. var result = '';
  25. if (reg.test(color)) {
  26. // 如果只有三位的值,需变成六位,如:#fff => #ffffff
  27. if (color.length === 4) {
  28. var colorNew = "#";
  29. for (var i = 1; i < 4; i += 1) {
  30. colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
  31. }
  32. color = colorNew;
  33. }
  34. // 处理六位的颜色值,转为RGB
  35. var colorChange = [];
  36. for (var i = 1; i < 7; i += 2) {
  37. colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
  38. }
  39. result = "rgb(" + colorChange.join(",") + ")";
  40. return { rgb: result, r: colorChange[0], g: colorChange[1], b: colorChange[2] };
  41. } else {
  42. result = '无效';
  43. return { rgb: result };
  44. }
  45. }
  46. };
  47. module.exports = colorChange