javascript get main color from image

Solutions on MaxInterview for javascript get main color from image by the best coders in the world

showing results for - "javascript get main color from image"
Fabio
24 Jan 2021
1const canvas = document.getElementById("canvas"),
2  preview = document.getElementById("preview"),
3  ctx = canvas.getContext("2d");
4
5canvas.width = 1;
6canvas.height = 1;
7
8preview.width = 400;
9preview.height = 400;
10
11function getDominantColor(imageObject) {
12  //draw the image to one pixel and let the browser find the dominant color
13  ctx.drawImage(imageObject, 0, 0, 1, 1);
14
15  //get pixel color
16  const i = ctx.getImageData(0, 0, 1, 1).data;
17
18  console.log(`rgba(${i[0]},${i[1]},${i[2]},${i[3]})`);
19
20  console.log("#" + ((1 << 24) + (i[0] << 16) + (i[1] << 8) + i[2]).toString(16).slice(1));
21}
22
23
24
25// vvv all of this is to just get the uploaded image vvv
26const input = document.getElementById("input");
27input.type = "file";
28input.accept = "image/*";
29
30input.onchange = event => {
31  const file = event.target.files[0];
32  const reader = new FileReader();
33
34  reader.onload = readerEvent => {
35    const image = new Image();
36    image.onload = function() {
37      //shows preview of uploaded image
38      preview.getContext("2d").drawImage(
39        image,
40        0,
41        0,
42        preview.width,
43        preview.height,
44      );
45      getDominantColor(image);
46    };
47    image.src = readerEvent.target.result;
48  };
49  reader.readAsDataURL(file, "UTF-8");
50};
51
52canvas {
53  width: 200px;
54  height: 200px;
55  outline: 1px solid #000000;
56}
57
58<canvas id="preview"></canvas>
59<canvas id="canvas"></canvas>
60<input id="input" type="file" />
61