Call Less.js Function In Javascript Has Different Output In Compare Node.js
during this question i want to call some less functions such as darken, lighten and spin inside javascript. i did it in node.js like this and it works: #!/usr/bin/env node var less
Solution 1:
As can be read from the comments the following code will give you #222222
:
var lessColor = {
lighten: function (color, amount) {
color = new (less.tree.Color)(color.substring(1));
amount = new(less.tree.Dimension)(amount, '%');
return less.tree.functions.lighten(color, amount).toRGB();
}
};
console.log(lessColor.lighten('#000',13.5));
Notice that color.substring(1)
just like col.replace(/#/g, '');
removes the starting #
. The input of less.tree.Color is the hex color triplet the less parser uses the following code for that conversion:
var rgb;
if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/))) {
var colorCandidateString = rgb.input.match(/^#([\w]+).*/); // strip colons, brackets, whitespaces and other characters that should not definitely be part of color string
colorCandidateString = colorCandidateString[1];
if (!colorCandidateString.match(/^[A-Fa-f0-9]+$/)) { // verify if candidate consists only of allowed HEX characterserror("Invalid HEX color code");
}
returnnew(tree.Color)(rgb[1]);
}
Solution 2:
Correcting the answer from @Bass Jobsen https://stackoverflow.com/a/26811314/3027390
In modern versions of Less there is no more less.tree.functions.lighten
.
You should use less.functions.functionRegistry.get('lighten')
instead.
That applies to any other Less function (not only color).
So, the updated answer should look like:
var lessColor = {
lighten: function (color, amount) {
color = new (less.tree.Color)(color.substring(1));
amount = new (less.tree.Dimension)(amount, '%');
func = less.functions.functionRegistry.get('lighten');
returnfunc(color, amount).toRGB();
}
};
console.log(lessColor.lighten('#000', 13.5)); // => '#222222'
Post a Comment for "Call Less.js Function In Javascript Has Different Output In Compare Node.js"