Skip to content

Instantly share code, notes, and snippets.

@sters
Created July 14, 2014 02:01
Show Gist options
  • Select an option

  • Save sters/3ca84e279d0541e2388e to your computer and use it in GitHub Desktop.

Select an option

Save sters/3ca84e279d0541e2388e to your computer and use it in GitHub Desktop.
#00FFAA + #112233 みたいなのを計算したかっただけ
//
// calcHTMLColor("#00FFAA + #112233");
// calcHTMLColor("#00FFAA - #445566");
//
function calcHTMLColor(expression) {
var replacer = [
{
regexp: /\#([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})/g,
callback: function(str, r, g, b) {
return "rgb(" + [r,g,b].map(function(n){ return parseInt(n, 16); }).join(",") + ")";
}
},
{
regexp: /\#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])/g,
callback: function(str, r, g, b) {
return "rgb(" + [r,g,b].map(function(n){ return parseInt(n, 16); }).join(",") + ")";
}
},
];
replacer.forEach(function(item) {
expression = expression.replace(item.regexp, item.callback);
});
console.log(expression);
function parseRGB(x) {
return x.match(/rgb\((.+)\)/)[1].split(",").map(function(n){ return parseInt(n); });
}
function toRGB(r,g,b) {
return "rgb(" + [r,g,b].join(",") + ")";
}
var append = expression.match(/(.+)(\+|\-)(.+)/);
if(append.length == 4) {
var a = parseRGB(append[1]);
var b = parseRGB(append[3]);
a = a.map(function(n, i){
var x = eval("n" + append[2] + "b[i]");
if(x>255) x = 255;
if(x<0) x = 0;
return x;
});
expression = toRGB.apply(this, a);
console.log(expression);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment