JavaScript按百分比混合三种颜色实现方案求助
三种颜色按百分比混合的JavaScript实现
当然可以实现三种颜色的混合。颜色混合的核心逻辑是对RGB三个通道分别进行加权求和——把每种颜色的红、绿、蓝分量各自乘以对应的百分比(转换为小数),再将三个颜色的对应分量结果相加,最终合并成新的RGB颜色值。
实现代码
首先需要一个辅助函数来解析常见的颜色格式(十六进制、rgb())为RGB数值:
// 辅助函数:将颜色字符串解析为{r: number, g: number, b: number} function parseColor(color) { // 处理十六进制颜色(支持3位或6位) if (color.startsWith('#')) { const hex = color.slice(1); let r, g, b; if (hex.length === 3) { r = parseInt(hex[0] + hex[0], 16); g = parseInt(hex[1] + hex[1], 16); b = parseInt(hex[2] + hex[2], 16); } else if (hex.length === 6) { r = parseInt(hex.slice(0, 2), 16); g = parseInt(hex.slice(2, 4), 16); b = parseInt(hex.slice(4, 6), 16); } else { throw new Error('无效的十六进制颜色格式'); } return { r, g, b }; } // 处理rgb()格式 if (color.startsWith('rgb(')) { const parts = color.slice(4, -1).split(',').map(str => parseInt(str.trim())); if (parts.length !== 3) throw new Error('无效的RGB颜色格式'); return { r: parts[0], g: parts[1], b: parts[2] }; } throw new Error('不支持的颜色格式,请使用十六进制或rgb()格式'); }
然后实现三种颜色混合的核心函数:
function mixColours(redColor, yellowColor, greenColor, redPercent, yellowPercent, greenPercent) { // 校验百分比总和是否为100(允许微小浮点误差) const total = redPercent + yellowPercent + greenPercent; if (Math.abs(total - 100) > 0.001) { throw new Error('三个百分比的总和必须为100'); } // 解析所有颜色为RGB分量 const redRGB = parseColor(redColor); const yellowRGB = parseColor(yellowColor); const greenRGB = parseColor(greenColor); // 计算每个通道的加权平均值(转换为小数) const r = Math.round(redRGB.r * (redPercent / 100) + yellowRGB.r * (yellowPercent / 100) + greenRGB.r * (greenPercent / 100)); const g = Math.round(redRGB.g * (redPercent / 100) + yellowRGB.g * (yellowPercent / 100) + greenRGB.g * (greenPercent / 100)); const b = Math.round(redRGB.b * (redPercent / 100) + yellowRGB.b * (yellowPercent / 100) + greenRGB.b * (greenPercent / 100)); // 确保值在0-255范围内 const clamp = val => Math.max(0, Math.min(255, val)); const finalR = clamp(r); const finalG = clamp(g); const finalB = clamp(b); // 返回十六进制格式的颜色(也可以返回rgb(${finalR}, ${finalG}, ${finalB})) return `#${((1 << 24) + (finalR << 16) + (finalG << 8) + finalB).toString(16).slice(1)}`; }
使用示例
// 示例:红(30%)、黄(50%)、绿(20%)混合 const result = mixColours('#ff0000', '#ffff00', '#00ff00', 30, 50, 20); console.log(result); // 输出 #ffcc33
如果需要支持更多颜色(4种及以上),可以把函数改造成接收颜色数组和百分比数组的形式,核心逻辑保持一致——遍历每个颜色的RGB分量进行加权求和即可。
内容的提问来源于stack exchange,提问作者M Usama
相关产品推荐
相关产品推荐

