Skip to content

Commit

Permalink
Update 将 rgb 颜色字符串转换为十六进制的形式.js
Browse files Browse the repository at this point in the history
  • Loading branch information
Rain120 authored Apr 2, 2019
1 parent de22daf commit 2a315e1
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions 将 rgb 颜色字符串转换为十六进制的形式.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,26 @@ function toHex(str) {
return ('0'+(+str).toString(16)).slice(-2);
}
rgb2hex('rgb(255, 255, 255)')

/*
* rgba -> { hex, hexa }
* (255, 0 , 255, 1) -> { hex: '#ff00ff', hexa: '#ff00ffff' }
*/
function rgba2hex(orig) {
var a,
rgb = orig.replace(/\s/g, '').match(/^(rgba|rgb)?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),
alpha = (rgb && rgb[4] || "").trim(),
hex = rgb ?
(rgb[1] | 1 << 8).toString(16).slice(1) +
(rgb[2] | 1 << 8).toString(16).slice(1) +
(rgb[3] | 1 << 8).toString(16).slice(1) : orig;

a = alpha !== "" ? alpha : '01';

a = ((a * 255) | 1 << 8).toString(16).slice(1);

return {
hex: '#' + hex,
hexa: '#' + hex + a,
};
}

0 comments on commit 2a315e1

Please sign in to comment.