javascript -按百分比混合三种颜色

kulphzqa  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(127)

在我的javascript应用程序中,我必须混合红、黄、绿色三种颜色。我必须按照为每种颜色指定的百分比来混合它们,比如:
mixColours(redColor, yellowColor, greenColor, redPercentage, yellowPercentage, greenPercentage)
我已经在SO上找到了this解决方案,但这只适用于两种颜色。
有可能实现三种颜色的混合吗?如果有,谁能分享一些代码吗?

3ks5zfa0

3ks5zfa01#

  • 提取颜色
  • 修圆最终颜色
const mixColours = (color1, color2, color3, percentage1, percentage2, percentage3) => {
    const red1 = parseInt(color1.slice(1, 3), 16);
    const green1 = parseInt(color1.slice(3, 5), 16);
    const blue1 = parseInt(color1.slice(5, 7), 16);
  
    const red2 = parseInt(color2.slice(1, 3), 16);
    const green2 = parseInt(color2.slice(3, 5), 16);
    const blue2 = parseInt(color2.slice(5, 7), 16);
  
    const red3 = parseInt(color3.slice(1, 3), 16);
    const green3 = parseInt(color3.slice(3, 5), 16);
    const blue3 = parseInt(color3.slice(5, 7), 16);
  
    const red = Math.round((red1 * percentage1 + red2 * percentage2 + red3 * percentage3) / (percentage1 + percentage2 + percentage3));
    const green = Math.round((green1 * percentage1 + green2 * percentage2 + green3 * percentage3) / (percentage1 + percentage2 + percentage3));
    const blue = Math.round((blue1 * percentage1 + blue2 * percentage2 + blue3 * percentage3) / (percentage1 + percentage2 + percentage3));
  
    return generateHex(red, green, blue);
};

希望能有所帮助

相关问题