c0lor
Version:
Color space conversions
86 lines (79 loc) • 1.86 kB
JavaScript
var O, createHsv, floor, hsv, hsvPrototype;
O = require("ut1l/create/object");
floor = Math.floor;
hsvPrototype = {
rgb: function(T) {
var f, h, p, q, t;
if (T == null) {
T = require("./rgb")();
}
if (this.s === 0) {
return T.set(this.v, this.v, this.v);
} else {
h = (this.h - floor(this.h)) * 6;
f = h - floor(h);
p = this.v * (1 - this.s);
q = this.v * (1 - this.s * f);
t = this.v * (1 - this.s * (1 - f));
switch (floor(h)) {
case 0:
return T.set(this.v, t, p);
case 1:
return T.set(q, this.v, p);
case 2:
return T.set(p, this.v, t);
case 3:
return T.set(p, q, this.v);
case 4:
return T.set(t, p, this.v);
case 5:
return T.set(this.v, p, q);
}
}
},
set: function(h1, s, v) {
this.h = h1;
this.s = s;
this.v = v;
return this;
},
toString: function() {
return "h=" + this.h + ", s=" + this.s + ", v=" + this.v;
}
};
hsv = createHsv = O((function(h1, s, v) {
this.h = h1;
this.s = s;
this.v = v;
}), hsvPrototype);
(require("./rgb")).extendRgb(function(rgb) {
return rgb.hsv = function(T) {
var d, max, min;
if (T == null) {
T = createHsv();
}
max = Math.max(this.r, this.g, this.b);
min = Math.min(this.r, this.g, this.b);
T.v = max;
d = max - min;
T.s = max !== 0 ? d / max : 0;
if (T.s === 0) {
T.h = 0;
} else {
switch (max) {
case this.r:
T.h = this.g < this.b ? 6 : 0;
T.h += (this.g - this.b) / d;
break;
case this.g:
T.h = 2 + (this.b - this.r) / d;
break;
default:
T.h = 4 + (this.r - this.g) / d;
}
T.h /= 6;
}
return T;
};
});
module.exports = hsv;