参考文档:https://kuangyx.cn
大致思路:把图片画到一张画布上,然后获取画布每个点的颜色,相同颜色最后的那个就是主题色,我觉这个思路获取到的数据相对来说是比较准确的,又看到其他人写的这个文章,但是大部分都是获取画布左上角的颜色,相对来说比较片面,所以最后选择了这个,好了,这就是大致的思路,具体实现代码往下看吧!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style>
img {
width: 300px;
}
</style>
<body>
<img src="https://qiniu.ve-link.com/files/4/d/f2/8666e5e6af0e58dda40ea323f029715302f9f2d4.png" id="img">
</body>
<script type="text/javascript">
const oImg = document.getElementById('img');
oImg.crossOrigin = ''
oImg.onload = function () {
const w = this.width;
const h = this.height;
// 创建画布
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
// 绘制图片在画布上
const context = canvas.getContext('2d');
context.drawImage(this, 0, 0);
// onload 内
let pxArr = context.getImageData(0, 0, w, h).data;
pxArr = Array.from(pxArr);
// onload 内
const colorList = {}
let i = 0;
while (i < pxArr.length) {
const r = pxArr[i];
const g = pxArr[i + 1];
const b = pxArr[i + 2];
// const a = pxArr[i + 3];
i = i + 4; // 最后 +4 比每次 i++ 快 10ms 左右性能
// const key = [r, g, b, a].join(',')
const key = [r, g, b].join(',')
key in colorList ? ++colorList[key] : (colorList[key] = 1)
}
// onload 内
let arr = [];
for (let key in colorList) {
arr.push({
rgba: `rgb(${key})`,
num: colorList[key]
})
}
arr = arr.sort((a, b) => b.num - a.num)
console.log(arr)
}
</script>
</html>
你担心什么,什么就控制你,加油!!!