Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript get main color from image

const canvas = document.getElementById("canvas"),
  preview = document.getElementById("preview"),
  ctx = canvas.getContext("2d");

canvas.width = 1;
canvas.height = 1;

preview.width = 400;
preview.height = 400;

function getDominantColor(imageObject) {
  //draw the image to one pixel and let the browser find the dominant color
  ctx.drawImage(imageObject, 0, 0, 1, 1);

  //get pixel color
  const i = ctx.getImageData(0, 0, 1, 1).data;

  console.log(`rgba(${i[0]},${i[1]},${i[2]},${i[3]})`);

  console.log("#" + ((1 << 24) + (i[0] << 16) + (i[1] << 8) + i[2]).toString(16).slice(1));
}



// vvv all of this is to just get the uploaded image vvv
const input = document.getElementById("input");
input.type = "file";
input.accept = "image/*";

input.onchange = event => {
  const file = event.target.files[0];
  const reader = new FileReader();

  reader.onload = readerEvent => {
    const image = new Image();
    image.onload = function() {
      //shows preview of uploaded image
      preview.getContext("2d").drawImage(
        image,
        0,
        0,
        preview.width,
        preview.height,
      );
      getDominantColor(image);
    };
    image.src = readerEvent.target.result;
  };
  reader.readAsDataURL(file, "UTF-8");
};

canvas {
  width: 200px;
  height: 200px;
  outline: 1px solid #000000;
}

<canvas id="preview"></canvas>
<canvas id="canvas"></canvas>
<input id="input" type="file" />
Comment

PREVIOUS NEXT
Code Example
Javascript :: netmask /24 
Javascript :: remove undefined element from array 
Javascript :: dropdown validation using jquery 
Javascript :: javascript slice vs splice 
Javascript :: faker random from array 
Javascript :: javascript array.find 
Javascript :: dockerfile 
Javascript :: js stop typing event 
Javascript :: bin2hex in js 
Javascript :: delete message discord.js 
Javascript :: javascript get nested element 
Javascript :: js base64 encoding 
Javascript :: how to run an existing react project 
Javascript :: how to convert array converted to string back to array javasccript 
Javascript :: map array method create object 
Javascript :: node get package.json version 
Javascript :: fat arrow function 
Javascript :: why does my form reload the page? html js 
Javascript :: js unspecified parameters 
Javascript :: reload datatable 
Javascript :: start pm2 node process with flags 
Javascript :: React Native Starting In Android 
Javascript :: set background image URL jQuery 
Javascript :: how to generate a random salt in nodejs 
Javascript :: js fast inverse square root 
Javascript :: callback hell javascript 
Javascript :: jquery select html element 
Javascript :: check if a key exists in an object javascript 
Javascript :: javascript array group by id 
Javascript :: get total width of element including padding and border using jquery 
ADD CONTENT
Topic
Content
Source link
Name
8+6 =