UNPKG

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