Question :
On my page I have several elements with different background colors. I would like to know how I could do to when clicking a button increase the brightness of the color, make it lighter.
You can do this using javascript / jquery ? How?
Answer :
Yes, it is possible. To do this you need to convert the color to HSV
to change the brightness.
Converting to HSV (to change brightness)
HSV
means Hue
(tone), Saturation
(saturation) and Value
(value). As the following image shows
v
,orValue
,correspondstothebrightness.
ThefollowingfunctionconvertsavalueRGB
toHSV
.
functionRgbToHsv(r,g,b){varmin=Math.min(r,g,b),max=Math.max(r,g,b),delta=max-min,h,s,v=max;v=Math.floor(max/255*100);if(max==0)return{h:0,s:0,v:0};s=Math.floor(delta/max*100);vardeltadiv=delta==0?1:delta;if(r==max)h=(g-b)/deltadiv;elseif(g==max)h=2+(b-r)/deltadiv;elseh=4+(r-g)/deltadiv;h=Math.floor(h*60);if(h<0)h+=360;return{h:h,s:s,v:v}}
NowthatIhavethecolorinHSV
IcanchangethevalueofV
tochangethebrightness.
ThenextstepistogetthevalueinRGB
toupdatethestyleoftheelement.ThefollowingfunctionconvertsfromHSV
toRGB
functionHsvToRgb(h,s,v){h=h/360;s=s/100;v=v/100;if(s==0){varval=Math.round(v*255);return{r:val,g:val,b:val};}hPos=h*6;hPosBase=Math.floor(hPos);base1=v*(1-s);base2=v*(1-s*(hPos-hPosBase));base3=v*(1-s*(1-(hPos-hPosBase)));if(hPosBase==0){red=v;green=base3;blue=base1}elseif(hPosBase==1){red=base2;green=v;blue=base1}elseif(hPosBase==2){red=base1;green=v;blue=base3}elseif(hPosBase==3){red=base1;green=base2;blue=v}elseif(hPosBase==4){red=base3;green=base1;blue=v}else{red=v;green=base1;blue=base2};red=Math.round(red*255);green=Math.round(green*255);blue=Math.round(blue*255);return{r:red,g:green,b:blue};}
Toillustrate,youcanusethefollowingmethod:
functionAppendColor(light){$(".dark").each(function(i){
// obtem a cor em RGB do elemento
var color = $(this).css("background-color");
color = color.replace(/[^0-9,]+/g, "");
var red = color.split(",")[0];
var gre = color.split(",")[1];
var blu = color.split(",")[2];
// converte rgb para hsv
var hsv = RgbToHsv(red,gre,blu);
// converte hsv para rgb modificando 'v'
var rgb = HsvToRgb(hsv.h, hsv.s, light);
// cria uma nova div e seta a nova cor
color = "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")";
$("<div />")
.css("background", color)
.attr("title", color)
.appendTo($(".light").parent());
$("<span />").html(" ").appendTo($(".light").parent())
});
$("<br />").appendTo($(".light").parent())
}
// Valores para teste
AppendColor(25);
AppendColor(50);
AppendColor(75);
AppendColor(90);
AppendColor(95);
AppendColor(97);
AppendColor(99);
AppendColor(100);
Result: