改善黑暗/亮度算法Javascript hex Color

时间:2015-05-22 22:02:22

标签: javascript algorithm

我需要一些帮助来找到为什么这个Darkness / Lightness算法Javascript hex颜色它在某些情况下失败了,请运行代码片段,我想了解为什么它的失败超过了解决方案,因为我将使用一个新的algorthim用hls颜色+%。

function similarColor(hex, percent) {
   console.log(hex);
		
   var a = parseInt(hex.substring(1,3),16);
   var b = parseInt(hex.substring(3,5),16);
   var c = parseInt(hex.substring(5,6),16);
				
   a = parseInt(a * (100 + percent) / 100);
   b = parseInt(b * (100 + percent) / 100);
   c = parseInt(c * (100 + percent) / 100);				
									
   a = (a<255)?a:255;  
   b = (b<255)?b:255;  
   c = (c<255)?c:255;  
  
   var aa = (a.toString(16).length==1)?"0"+a.toString(16):a.toString(16);
   var bb = (b.toString(16).length==1)?"0"+b.toString(16):b.toString(16);
   var cc = (c.toString(16).length==1)?"0"+c.toString(16):c.toString(16);
				
   return "#"+aa+bb+cc;
}

//Error
document.getElementById('errorColor').style.backgroundColor=similarColor('#074E7C', 50);


//Well working
  document.getElementById('newColor2').style.backgroundColor=similarColor('#2A7C2A', 50);
document.getElementById('newColor3').style.backgroundColor=similarColor('#FC1479', 50); 
document.getElementById('newColor4').style.backgroundColor=similarColor('#FCFC6F', 50);
Error<br>
<div style="background-color:#074E7C">#074E7C</div>
<div id="errorColor">lightness</div>
<hr> 
Correct<br>
<div style="background-color:#2A7C2A">original</div>
<div id="newColor2">lightness</div>
<hr>
Looks bad<br>
<div style="background-color:#FC1479">original</div>
<div id="newColor3">lightness</div>
<hr>
Correct<br>
<div style="background-color:#FCFC6F">original</div>
<div id="newColor4">lightness</div>
<hr>

1 个答案:

答案 0 :(得分:0)

我的坏, 在此示例中,错误是因为代码丢失了十六进制存储桶的最后一个字符。 var C为7 =蓝色,但应为7C =黑绿色。固定行:var c = parseInt(hex.substring(5,7),16);