随机生成两种颜色略有不同的颜色

Randomly generate two colors with a slight difference in shade

我正在尝试随机使用JS生成一对RGB格式的颜色,它们彼此相似但颜色略有不同。

请参阅下面的参考图片,所有 3 "cases"(这将是 随机 生成的)如何包含两种颜色,两种颜色非常相似,但是略有不同的色调。

我尝试了下面的代码,但是生成的颜色完全不同。

如何 我可以让第二种颜色与第一种颜色略有不同,而这对颜色是用随机值生成的?

ran1 = Math.floor(Math.random() * 255) + 1;
ran2 = Math.floor(Math.random() * 255) + 1;
ran3 = Math.floor(Math.random() * 255) + 1;
ran4 = Math.floor(Math.random() * 255) + 1;
ran5 = Math.floor(Math.random() * 255) + 1;
ran6 = Math.floor(Math.random() * 255) + 1;

color1 = "rgb(" + ran1 + "," + ran2 + "," + ran3 + ")"; // random color
color2 = "rgb(" + ran4 + "," + ran5 + "," + ran6 + ")"; // probably dissimilar to color1

这里会提供两种深浅略有不同的颜色,只是演示一个原理,有待扩展;它不是一个打包的、完美的、生产就绪的解决方案。

基本上,它会增加第二种颜色的 RGB 值,如果第一种颜色的 RGB 值还不是太高的话,它会比第一种多一点。

const slightness = 20; // positive for slightly lighter color

const colors = document.querySelectorAll( "div" ),
      color1 = colors[ 0 ],
      color2 = colors[ 1 ];

function shallWe( c ) {
  return c < 236 ? slightness : 0;
}

let ran1 = Math.floor(Math.random() * 255) + 1,
    ran2 = Math.floor(Math.random() * 255) + 1,
    ran3 = Math.floor(Math.random() * 255) + 1;

color1.style.background = "rgb(" + ran1 + "," + ran2 + "," + ran3 + ")";
ran1 += shallWe( ran1 );
ran2 += shallWe( ran2 );
ran3 += shallWe( ran3 );
color2.style.background = "rgb(" + ran1 + "," + ran2 + "," + ran3 + ")";
div { padding: 2em; }
<div></div><div></div>