RBG转灰度
//rgba(grey,grey,grey,1) function rgb2Grey(r,g,b) { var grey=Math.round((r*299 + g*587 + b*114 + 500) / 1000) return grey }
判断两种颜色相似程度
//rbg function isSimilarColorRBG(r1, g1, b1, r2, g2, b2, offset) { if (Math.sqrt((r1 - r2) * (r1 - r2) + (g1 - g2) * (g1 - g2) + (b1 - b2) * (b1 - b2)) < offset) { return true; } else { return false; } } //hex function isSimilarColorHEX(sHexColorA, sHexColorB, nOffset) { this.offsetNum = Math.abs(nOffset); this.offsetNum > 255 ? this.offsetNum = this.offsetNum - 256 : ""; var arrNumA = [parseInt(sHexColorA.substring(0, 2), 16), parseInt(sHexColorA.substring(2, 4), 16), parseInt(sHexColorA.substring(4, 6), 16) ]; var arrNumB = [parseInt(sHexColorB.substring(0, 2), 16), parseInt(sHexColorB.substring(2, 4), 16), parseInt(sHexColorB.substring(4, 6), 16) ]; for (var i = 0; i < arrNumA.length; i++) { if (Math.abs(arrNumA[i] - arrNumB[i]) > this.offsetNum) { return false;//不相似 }; } return true;//相似 }
RGB转HEX
//rgb2Hex("rbg(r,g,b)") function rgb2Hex(rgb) { var color = rgb.toString().match(/d+/g); var hex = "#"; for (var i = 0; i < 3; i++) { hex += ("0" + Number(color[i]).toString(16)).slice(-2); } return hex; }
HEX转RGB
//hex2Rgb("#ff00ff") function hex2Rgb(a) { if (a.substr(0, 1) == "#") a = a.substring(1); var len = a.length; a = a.toLowerCase(); var b = new Array(); for (x = 0; x < 3; x++) { b[0] = len == 6 ? a.substr(x * 2, 2) : a.substr(x * 1, 1) + a.substr(x * 1, 1); b[3] = "0123456789abcdef"; b[1] = b[0].substr(0, 1); b[2] = b[0].substr(1, 1); b[20 + x] = b[3].indexOf(b[1]) * 16 + b[3].indexOf(b[2]) } console.log(b[20] + "," + b[21] + "," + b[22]); }