support for hsl(), rgb() etc

This commit is contained in:
cloudhead 2010-03-01 21:48:19 -05:00
parent 60ac2374c9
commit 2682b6dc16
2 changed files with 35 additions and 13 deletions

View File

@ -5,12 +5,17 @@ tree.functions = {
return this.rgba(r, g, b, 1.0);
},
rgba: function (r, g, b, a) {
return new(tree.Color)([r, g, b, a]);
var rgb = [r, g, b].map(function (c) { return number(c) }),
a = number(a);
return new(tree.Color)(rgb, a);
},
hsl: function (h, s, l) {
return this.hsla(h, s, l, 1.0);
},
hsla: function (h, s, l, a) {
h = number(h); s = number(s);
l = number(l); a = number(a);
var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
var m1 = l * 2 - m2;
@ -26,3 +31,15 @@ tree.functions = {
}
};
function number(n) {
if (n instanceof tree.Dimension) {
return parseFloat(n.value);
} else if (typeof(n) === 'number') {
return n;
} else {
throw {
error: "RuntimeError",
message: "color functions take numbers as parameters"
};
}
}

View File

@ -2,15 +2,16 @@ if (typeof(window) === 'undefined') { var tree = require(require('path').join(__
//
// RGB Colors - #ff0014, #eee
//
tree.Color = function Color(val) {
if (Array.isArray(val)) {
this.value = val;
} else if (val.length == 6) {
this.value = val.match(/.{2}/g).map(function (c) {
tree.Color = function Color(rgb, a) {
if (Array.isArray(rgb)) {
this.rgb = rgb;
this.alpha = a;
} else if (rgb.length == 6) {
this.rgb = rgb.match(/.{2}/g).map(function (c) {
return parseInt(c, 16);
});
} else {
this.value = val.split('').map(function (c) {
this.rgb = rgb.split('').map(function (c) {
return parseInt(c + c, 16);
});
}
@ -18,11 +19,15 @@ tree.Color = function Color(val) {
tree.Color.prototype = {
eval: function () { return this },
toCSS: function () {
return '#' + this.value.map(function (i) {
i = Math.round(i);
i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16);
return i.length === 1 ? '0' + i : i;
}).join('');
if (this.alpha && this.alpha < 1.0) {
return "rgba(" + this.rgb.concat(this.alpha).join(', ') + ")";
} else {
return '#' + this.rgb.map(function (i) {
i = Math.round(i);
i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16);
return i.length === 1 ? '0' + i : i;
}).join('');
}
},
operate: function (op, other) {
var result = [];
@ -31,7 +36,7 @@ tree.Color.prototype = {
}
for (var c = 0; c < 3; c++) {
result[c] = node.operate(op, this.value[c], other.value[c]);
result[c] = tree.operate(op, this.rgb[c], other.rgb[c]);
}
return new(tree.Color)(result);
}