📜  javascript 从图像中获取主颜色 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:02:44.629000             🧑  作者: Mango

代码示例1
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;
}