Osama Abbas Osama Abbas - 1 year ago 56
Javascript Question

Javascript - Convert and Display Array of Number into Colors

I am using Color-Thief to extract a color palette from an image. And I've already extracted the colors using JavaScript.

<img src="my-image.jpg" id="uploadedImage" alt="Uplaoded Image>

<script type="text/javascript">
var image = document.getElementById("uploadedImage");
var colorThief = new ColorThief();
var palette = colorThief.getPalette(image, 8);
for (color in palette) {
var firstColor = palette[0];
var secondColor = palette[1];
var thirdColor = palette[2];
var fourthColor = palette[3];
var fifthColor = palette[4];
var sixthColor = palette[5];
var seventhColor = palette[6];
var eighthColor = palette[7];
}

</script>


The colors extracted for example are:

(7) [Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3)]
0
:
(3) [55, 30, 41]
1
:
(3) [210, 111, 74]
2
:
(3) [121, 196, 212]
3
:
(3) [144, 62, 57]
4
:
(3) [101, 66, 100]
5
:
(3) [189, 174, 192]
6
:
(3) [164, 116, 133]


But my problem is that I cannot convert these Arrays into colors to display. Is there any way to do that?

I have read this question, but the answer doesn't help me figure out the way to solve my problem.

The answer to this question doesn't consider getting the colors dynamically from images neither displaying the colors. It's just converting from one space to another.


SIDE NOTE: If you want to try the Color-Thief, you have to have a server, because it calls AJAX.

Answer Source

If you have array of arrays, where each of the sub arrays has 3 items representing the R, B and G, you can convert them to hexadecimal notation using the link in your question:

ar = [
  [55, 30, 41],
  [210, 111, 74],
  [121, 196, 212],
  [144, 62, 57],
  [101, 66, 100],
  [189, 174, 192],
  [164, 116, 133]
]
res = ar.map(([r, g, b]) => ["#", r.toString(16), g.toString(16), b.toString(16)].join(""))
console.log(res);

document.getElementById("container").innerHTML = res.map((color) => `<div class='color-box' style='background: ${color};'></div>`).join("")
div.color-box {
  width: 50px;
  height: 50px;
  margin: 15px;
  float: left;
}
<div id="container"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download