Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get shades of Color in Javascript or jQuery?

Is there a way in Javascript or jQuery that we can get all shades of a color and then return the values into an array? Thank you very much.

Something like:

enter image description here

like image 756
Lan Mai Avatar asked Dec 08 '22 19:12

Lan Mai


2 Answers

In color theory, to get a shade of a color you need to reduce its lightness, and to get a tint of a color you need to increase its lightness. I've created a library, that allows you to work with the HSL color model. With this color model, you can take a base color and change its hue, lightness, or saturation. Here you have something similar to your purposes using the getTints method:

const container = document.querySelector("#container");
const tints = ColorTranslator.getTints("#93625D", 15);

tints.forEach((c) => {
  const box = document.createElement("div");
  box.style.backgroundColor = c;
  container.appendChild(box);
});

console.log(JSON.stringify(tints));
html,
body {
  height: 100%;
}

#container {
  display: flex;
  height: 100%;
}

#container div {
  height: 100%;
  width: 100%;
}
<script src="https://unpkg.com/[email protected]/dist/colortranslator.web.js"></script>

<div id="container">
</div>

Here you have another example that changes the saturation and lightness of a color at the same time to get all the tints of each saturation:

const container = document.querySelector("#container");
const color = new ColorTranslator('hsl(25,100%,50%)');
let box = null;

//---Create elements
for (let row = 0; row < 10; row++) {

  for (let col = 0; col < 10; col++) {

    color
      .setS(row * 10)
      .setL(col * 5 + 30);

    box = document.createElement("div");
    box.style.background = color.HEX;
    box.innerText =
      `R:${color.R}
       G:${color.G}
       B:${color.B}`;
    container.appendChild(box);

  }

}
html,
body {
  height: 500px;
}

body {
  margin: 0;
  padding: 0;
  position: relative;
}

#container {
  display: flex;
  flex-wrap: wrap;
  height: 500px;
  margin: 0 auto;
  position: relative;
  width: 500px;
}

#container div {
  align-items: center;
  box-sizing: border-box;
  display: flex;
  font-family: Arial;
  font-size: 10px;
  height: 10%;
  justify-content: center;
  text-align: center;
  width: 10%;
}
<script src="https://unpkg.com/[email protected]/dist/colortranslator.web.js"></script>

<div id="container">
</div>
like image 192
ElChiniNet Avatar answered Dec 10 '22 09:12

ElChiniNet


Do you mean something like this?

var r = 40 % 256;
var g = 40 % 256;
var b = 50 % 256;
var result = [];

for(var i = 0; i < 7; i++)
{
    r += 33;
    g += 33;
    b += 33;
    result.push(r + "," + g + "," + b);
}
  
console.log(result);
like image 35
Mazz Avatar answered Dec 10 '22 09:12

Mazz