js: color-thief在浏览器中拾取图片的主色调
发布时间:2022-10-10 15:30:46 413
相关标签: # npm# git# github
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
使用示例
浏览器中
<script src="https://cdnjs.cloudflare.com/ajax/libs/color-thief/2.3.0/color-thief.umd.js"></script>
<script>
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";
</script>
一个简单实现
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...
文章来源: https://blog.51cto.com/u_13567403/5739862
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报