UNPKG

2.46 kBJavaScriptView Raw
1var Colr = function () {
2 this.r = 0;
3 this.g = 0;
4 this.b = 0;
5};
6
7Colr.fromHex = function (hex) {
8 var colr = new Colr();
9 colr.fromHex(hex);
10 return colr;
11};
12
13Colr.fromRgb = function (r, g, b) {
14 var colr = new Colr();
15 colr.fromRgb(r, g, b);
16 return colr;
17};
18
19Colr.fromRgbArray = function (arr) {
20 var colr = new Colr();
21 colr.fromRgbArray(arr);
22 return colr;
23};
24
25Colr.fromRgbObject = function (obj) {
26 var colr = new Colr();
27 colr.fromRgbObject(obj);
28 return colr;
29};
30
31Colr.prototype.fromHex = function (hex) {
32 if (typeof hex !== 'string') {
33 throw new Error('colr.fromHex: requires string');
34 }
35 if (hex[0] === '#') {
36 hex = hex.slice(1);
37 }
38 if (! hex.match(/^[0-9a-f]*$/i)) {
39 throw new Error('colr.fromHex: invalid hex characters');
40 }
41 if (hex.length >= 6) {
42 this.r = parseInt(hex.slice(0,2), 16);
43 this.g = parseInt(hex.slice(2,4), 16);
44 this.b = parseInt(hex.slice(4,6), 16);
45 } else if (hex.length >= 3){
46 this.r = parseInt(hex[0] + hex[0], 16);
47 this.g = parseInt(hex[1] + hex[1], 16);
48 this.b = parseInt(hex[2] + hex[2], 16);
49 } else {
50 throw new Error('colr.fromHex: invalid hex length');
51 }
52 this._sanitize();
53 return this;
54};
55
56Colr.prototype.fromRgb = function (r, g, b) {
57 if (typeof r != 'number' || typeof g != 'number' || typeof b != 'number') {
58 throw new Error('colr.fromRgb requires three numbers');
59 }
60 this.r = r;
61 this.g = g;
62 this.b = b;
63 this._sanitize();
64 return this;
65};
66
67Colr.prototype.fromRgbArray = function (arr) {
68 return this.fromRgb.apply(this, arr);
69};
70
71Colr.prototype.fromRgbObject = function (obj) {
72 return this.fromRgb(obj.r, obj.g, obj.b);
73};
74
75Colr.prototype.toHex = function () {
76 var r = this.r.toString(16);
77 var g = this.g.toString(16);
78 var b = this.b.toString(16);
79 if (r.length < 2) r = '0' + r;
80 if (g.length < 2) g = '0' + g;
81 if (b.length < 2) b = '0' + b;
82 return ('#' + r + g + b).toUpperCase();
83};
84
85Colr.prototype.toRgbArray = function () {
86 return [ this.r, this.g, this.b ];
87};
88
89Colr.prototype.toRgbObject = function () {
90 return {
91 r: this.r,
92 g: this.g,
93 b: this.b,
94 };
95};
96
97Colr.prototype.clone = function () {
98 var colr = new Colr();
99 colr.fromRgbArray(this.toRgbArray());
100 return colr;
101};
102
103Colr.prototype._sanitize = function () {
104 this.r = Math.max(0, Math.min(255, this.r));
105 this.g = Math.max(0, Math.min(255, this.g));
106 this.b = Math.max(0, Math.min(255, this.b));
107};
108
109module.exports = Colr;