var myData = { canvas : document.getElementById('colors'),
// context : myData.canvas.getContext('2d'); //这样做会导致程序出错,应该在函数中获取画布 canvasColor : document.getElementById('color'), plus : document.getElementsByClassName('plusButton'), subtract : document.getElementsByClassName('subtractButton'), red : document.getElementById('red'), green : document.getElementById('green'), blue : document.getElementById('blue'), hue : document.getElementById('hue'), saturation : document.getElementById('saturation'), lightness : document.getElementById('lightness'), x:0, y:0 };
//这小段代码是设置RGB和HSL的增减,,点击后面的三角则值加减
function setRGBorHSL(){ var colorInput = document.getElementsByClassName('colorInput'); var color; for(var i = 0;i < myData.plus.length/2;i++){ myData.plus[i].dataset.index = i;//用到了自定义属性,是个小技能,因为前面的输入框的下标会直接跳到i最大的值,就是先循环后,再将i赋值给表单下标,所以给要绑定 事件的三角元素,绑定事件就会对相应的表单值进行加减操作 myData.subtract[i].dataset.index = i; addEvent(myData.plus[i],'click',function(){ var temp = colorInput[this.dataset.index].value; var hsl = []; temp = (temp > 254?temp:++temp); colorInput[this.dataset.index].value = temp; hsl = rgbToHsl(parseInt(myData.red.value),parseInt(myData.green.value),parseInt(myData.blue.value)); color = '#'+parseInt(myData.red.value).toString(16)+parseInt(myData.green.value).toString(16)+ parseInt(myData.blue.value).toString(16); setColorBlock(color,false); myData.hue.value = hsl[0].toFixed(2); myData.saturation.value = hsl[1].toFixed(2); myData.lightness.value = hsl[2].toFixed(2); })
RGB和HSL之间的转换
//RGB转换为HSL function rgbToHsl(r, g, b){ r /= 255, g /= 255, b /= 255; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; if(max == min){ h = s = 0; // achromatic }else{ var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch(max){ case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return [h, s, l]; } //hsl转换为RGB function hslToRgb(h, s, l){ var r, g, b; if(s == 0){ r = g = b = l; // achromatic }else{ var hue2rgb = function hue2rgb(p, q, t){ if(t < 0) t += 1; if(t > 1) t -= 1; if(t < 1/6) return p + (q - p) * 6 * t; if(t < 1/2) return q; if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; } var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1/3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1/3); } return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; }
这个小东西主要用canvas