在浏览器环境中,可以通过canvas 获取图片的颜色列表,再对其进行排序,就能获取图片颜色主色调了,也可以使用开源库,可以很方便的获取图片颜色
目录
- rgbaster
- color-thief
- canvas
rgbaster
文档
安装
npm i rgbaster
rgbaster会返回如下结果
[
{ color: 'rgb(0,0,255)', count: 86 },
{ color: 'rgb(9,18,42)', count: 32 },
{ color: 'rgb(120,8,202)', count: 3 },
]
示例
import rgbaster from 'rgbaster'
let res = await rgbaster('图片url', { scale: 0.6 });
// 获取图片主色
res[0].color
color-thief
- github https://github.com/lokesh/color-thief
- npmjs https://www.npmjs.com/package/colorthief
- 文档 https://lokeshdhakar.com/projects/color-thief/
canvas
使用canvas获取图片颜色的方法
<canvas id="canvas"></canvas>
<script>
// 步骤一:创建 Canvas 元素
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// 步骤二:绘制图片到 Canvas 上
var img = new Image();
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
getImageColors();
};
img.src = "image.jpg";
// 步骤三:遍历像素点获取颜色值
function getImageColors() {
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data = imageData.data;
var colors = [];
for (var i = 0, len = data.length; i < len; i += 4) {
var r = data[i];
var g = data[i + 1];
var b = data[i + 2];
var a = data[i + 3];
colors.push([r, g, b, a]);
}
console.log(colors);
}
</script>
参考文章