Grab the color palette from an image using just Javascript. Works in the browser and in Node.
译文:使用Javascript从图像中抓取调色板。在浏览器和Node.js中工作。
文档:
- https://github.com/lokesh/color-thief
- https://lokeshdhakar.com/projects/color-thief/
- https://www.npmjs.com/package/color-thief
使用示例
浏览器中
const colorThief = new ColorThief();
const img = new Image();
img.addEventListener("load", function () {
let color = colorThief.getColor(img);
console.log(color);
// [125, 190, 193]
});
img.crossOrigin = "Anonymous";
img.src = "./image.jpg";
一个简单实现
const img = new Image();
img.crossOrigin = 'Anonymous';
img.src = "./image.jpg";
img.setAttribute("width", 1);
img.setAttribute("height", 1);
img.onload = () => {
const canvas = new OffscreenCanvas(1, 1);
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, 1, 1);
const { data } = ctx.getImageData(0, 0, 1, 1);
console.log(`rgba(${data.join(",")})`);
// rgba(120,143,122,255)
};
参考 你的图片加载,一点都不酷炫!不信You Look Look…