js实现颜色
颜色表示方法
在JavaScript中,颜色可以通过多种方式表示,包括十六进制、RGB、RGBA、HSL和HSLA等格式。
十六进制格式:
const hexColor = '#FF5733';
RGB格式:
const rgbColor = 'rgb(255, 87, 51)';
RGBA格式(带透明度):
const rgbaColor = 'rgba(255, 87, 51, 0.5)';
HSL格式:
const hslColor = 'hsl(12, 100%, 60%)';
HSLA格式(带透明度):
const hslaColor = 'hsla(12, 100%, 60%, 0.5)';
颜色转换
将RGB转换为十六进制:
function rgbToHex(r, g, b) {
return '#' + [r, g, b].map(x => x.toString(16).padStart(2, '0')).join('');
}
将十六进制转换为RGB:
function hexToRgb(hex) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return { r, g, b };
}
随机颜色生成
生成随机十六进制颜色:
function randomHexColor() {
return '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
}
生成随机RGB颜色:
function randomRgbColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
}
颜色操作
调整颜色亮度:
function adjustBrightness(hex, percent) {
const { r, g, b } = hexToRgb(hex);
const adjust = (value) => Math.min(255, Math.max(0, value + Math.round(255 * (percent / 100))));
return rgbToHex(adjust(r), adjust(g), adjust(b));
}
混合两种颜色:
function blendColors(color1, color2, ratio) {
const c1 = hexToRgb(color1);
const c2 = hexToRgb(color2);
const r = Math.round(c1.r * ratio + c2.r * (1 - ratio));
const g = Math.round(c1.g * ratio + c2.g * (1 - ratio));
const b = Math.round(c1.b * ratio + c2.b * (1 - ratio));
return rgbToHex(r, g, b);
}
颜色验证
验证是否为有效十六进制颜色:
function isValidHexColor(hex) {
return /^#([0-9A-F]{3}){1,2}$/i.test(hex);
}
验证是否为有效RGB颜色:
function isValidRgbColor(rgb) {
return /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/.test(rgb);
}
颜色名称映射
将颜色名称映射为十六进制值:
const colorNameToHex = {
'red': '#FF0000',
'green': '#00FF00',
'blue': '#0000FF',
'black': '#000000',
'white': '#FFFFFF'
};
获取颜色名称对应的十六进制值:
function getHexFromName(colorName) {
return colorNameToHex[colorName.toLowerCase()] || null;
}





