2015-05-22 67 views
0

我需要一些幫助來找到爲什麼這個黑暗/亮度算法Javascript十六進制顏色它在某些情況下失敗,請運行該片段,我想明白爲什麼它的失敗不止有一個解決方案,因爲我將使用帶有hls顏色+%的新algorthim。改善黑暗/亮度算法Javascript十六進制顏色

function similarColor(hex, percent) { 
 
    console.log(hex); 
 
\t \t 
 
    var a = parseInt(hex.substring(1,3),16); 
 
    var b = parseInt(hex.substring(3,5),16); 
 
    var c = parseInt(hex.substring(5,6),16); 
 
\t \t \t \t 
 
    a = parseInt(a * (100 + percent)/100); 
 
    b = parseInt(b * (100 + percent)/100); 
 
    c = parseInt(c * (100 + percent)/100); \t \t \t \t 
 
\t \t \t \t \t \t \t \t \t 
 
    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); 
 
\t \t \t \t 
 
    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

算法應該做什麼?你有什麼問題? – joews

+1

它可能是var c = parseInt(hex.substring(5,7),16); ? – b2238488

+0

@ b2238488是的,我的不好,謝謝 jamesjara

回答

0

我的壞, 在這個例子中的錯誤是由於代碼缺少六角桶的最後一個字符。 var C是7 =藍色,但應該是7C = blackgreen。固定線路:var c = parseInt(hex.substring(5,7),16);