Color Thief
仅使用 Javascript 从图像中获取调色板。 在浏览器和 Node 中工作。
官网链接:Color Thief
入门
Color Thief 包包含多个分发文件以支持不同的环境和构建过程。以下是 /dist 文件夹中所有文件及其支持的格式的列表:
- color-thief.js - 用于 Node.js 中的 CommonJS 模块。
- color-thief.mjs - ES6 模块。适用于现代浏览器以及 Webpack 和 Rollup。
- color-thief.umd.js - UMD模块。用于公开全局变量的简单脚本标记加载或用于 RequireJS AMD 支持。
- color-thief.min.js - color-thief.umd.js 的重复项。保留以保持向后兼容性。
Node
-
安装并导入
$ npm i --save colorthief
-
获取colors。getColor() 和 getPalette() 方法在 Node 中使用时都会返回 Promise。
const img = resolve(process.cwd(), 'rainbow.png'); ColorThief.getColor(img) .then(color => { console.log(color) }) .catch(err => { console.log(err) }) ColorThief.getPalette(img, 5) .then(palette => { console.log(palette) }) .catch(err => { console.log(err) })
browser
- 安装 在浏览器中使用 Color Thief 时,有多种安装方法:
-
npm 依赖
$ npm i --save colorthief
-
CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/color-thief/2.3.0/color-thief.umd.js"></script>
-
github下载
您可以从项目的Github 版本页面下载最新版本(或任何先前版本)的 zip。
- 导入和使用 在浏览器中使用 Color Thief 时,有多种安装方法:
-
全局变量
<script src="node_modules/colorthief/dist/color-thief.umd.js"></script> <script> const colorThief = new ColorThief(); const img = document.querySelector('img'); // Make sure image is finished loading if (img.complete) { colorThief.getColor(img); } else { image.addEventListener('load', function() { colorThief.getColor(img); }); } </script>
-
ES6模块
index.html<script type="module" src="app.js"></script>
app.js
import ColorThief from './node_modules/colorthief/dist/color-thief.mjs' const colorThief = new ColorThief(); const img = document.querySelector('img'); if (img.complete) { colorThief.getColor(img); } else { image.addEventListener('load', function() { colorThief.getColor(img); }); }
-
RequireJS
/dist/color-thief.umd.js
文件使用 UMD(通用模块定义)格式。这包括 RequireJS AMD 支持。
util.js
// rgb转16进制
export function rgbToHex(r, g, b) {
return `#${[r, g, b].map((x) => {
const hex = x.toString(16)
return hex.length === 1 ? `0${hex}` : hex
}).join('')}`
}
// 获取color
export async function getColors(url, amount = 5) {
const img = document.createElement('img')
await new Promise((resolve) => {
img.onload = () => resolve()
img.src = url
})
const palette = new window.ColorThief().getPalette(img, amount)
return palette.map(rgb => rgbToHex(...rgb))
}
API
注意:在 Node.js 中使用时,getColor
和 getPalette
都会返回一个 Promise
。
getColor(image [, quality])
Returns: [Number, Number, Number]
获取图像的主色。颜色以三个整数的数组形式返回,分别代表红色、绿色和蓝色值。
image
- 在浏览器中调用时,此参数需要 HTML 图像元素,而不是 URL。在 Node 中运行时,此参数需要图像的路径。
quality
- 是一个可选参数,必须是值 1 或更大的整数,默认为 10,该数字决定了在采样下一个像素之前跳过多少个像素。数字越大,返回值的速度越快。
getPalette(image [, colorCount, quality]
Returns: [[Number, Number, Number], …]
通过聚集相似的颜色从图像中获取调色板。调色板作为包含颜色的数组返回,每种颜色本身是一个由三个整数组成的数组。