on be72e86 help sign in
elk/libraries/Native/Color.js
65 lines 1.7 kB history raw
3Elm.Native.Color = function(elm) {
4 "use strict";
6 elm.Native = elm.Native || {};
7 if (elm.Native.Color) return elm.Native.Color;
9 function complement(rgb) {
10 var hsv = toHSV(rgb);
11 hsv.hue = (hsv.hue + 180) % 360;
12 return toRGB(hsv);
13 }
15 function hsva(h,s,v,a) {
16 var clr = toRGB({hue:h, saturation:s, value:v});
17 clr._3 = a;
18 return clr;
19 }
21 function hsv(h,s,v) { return toRGB({hue:h, saturation:s, value:v}); }
23 function toHSV(rgb) {
24 var hsv = {};
25 var r = rgb._0 / 255.0, g = rgb._1 / 255.0, b = rgb._2 / 255.0;
26 var M = Math.max(r,g,b);
27 var m = Math.min(r,g,b);
28 var c = M - m;
30 var h = 0;
31 if (c === 0) { h = 0; }
32 else if (M === r) { h = ((g - b) / c) % 6; }
33 else if (M === g) { h = ((b - r) / c) + 2; }
34 else if (M === b) { h = ((r - g) / c) + 4; }
35 h *= 60;
37 return { value : M, hue : h, saturation : (M === 0 ? 0 : c / M) };
38 }
40 function between(lo,hi,x) { return lo <= x && x < hi; }
41 function norm(n) { return Math.round(n*255); }
43 function toRGB(hsv) {
44 var c = hsv.value * hsv.saturation;
45 var hue = hsv.hue / 60;
46 var x = c * (1 - Math.abs((hue % 2) - 1));
47 var r = 0, g = 0, b = 0;
48 if (between(0,1,hue)) { r = c; g = x; b = 0; }
49 else if (between(1,2,hue)) { r = x; g = c; b = 0; }
50 else if (between(2,3,hue)) { r = 0; g = c; b = x; }
51 else if (between(3,4,hue)) { r = 0; g = x; b = c; }
52 else if (between(4,5,hue)) { r = x; g = 0; b = c; }
53 else if (between(5,6,hue)) { r = c; g = 0; b = x; }
55 var m = hsv.value - c;
56 return { ctor:"Color", _0:norm(r+m), _1:norm(g+m), _2:norm(b+m), _3:1 };
57 }
59 return elm.Native.Color = {
60 hsva:F4(hsva),
61 hsv:F3(hsv),
62 complement:complement
63 };
65};