前提

在使用APlayer的时候发现了有能根据音乐封面自适应主题颜色,这是第一次接触js的时候,不能说是一点不会,只能说是一窍不通,直接复制官网代码过来也用不了,发现错误了但是是英文,导致开始下载翻译软件,开始百度,后面发现错误在最后一句setTheme(index),得益于js的缺点,导致百度白天也没找到解决方案,到最后才发现index是一个对象,下面还有一个index,需要调用索引setTheme(index.index)这样才有效。

后面看这个js的时候发现它可以根据图片的颜色来获取主色调,博客是有自动获取获取封面主色调的函数的,但是需要图片存放在有数据万象功能的存储桶里,但是需要亿点点的money,本着能白嫖就白嫖的想法,想了一下,把这个插件整合到博客中去,结果很成功,会拖慢一点点的响应速度。免费的还要什么自行车

下面是官网的函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const colorThief = new ColorThief();
const image = new Image();
const xhr = new XMLHttpRequest();
const setTheme = (index) => {
if (!ap.list.audios[index].theme) {
xhr.onload = function(){
let coverUrl = URL.createObjectURL(this.response);
image.onload = function(){
let color = colorThief.getColor(image);
ap.theme(`rgb(${color[0]}, ${color[1]}, ${color[2]})`, index);
URL.revokeObjectURL(coverUrl)
};
image.src = coverUrl;
}
xhr.open('GET', ap.list.audios[index].cover, true);
xhr.responseType = 'blob';
xhr.send();
}
};
setTheme(ap.list.index);
ap.on('listswitch', (index) => {
setTheme(index); //错误在这
});

引入js

找到 _config.butterfly.yml文件,在inject的bottom引入js

1
2
3
4
inject:

bottom:
- <script data-pjax async type="text/javascript" src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/color-thief/2.3.2/color-thief.umd.js"></script>

下面这段js需要插入到主题下的source/main.js函数中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const coverColor = async () => {
const root = document.querySelector(":root");
var path = document.getElementById("post-top-bg")?.src;//获取封面路径
const colorThief = new ColorThief();//创建一个颜色提取器
const image = new Image();//创建一个图片对象
if (path != undefined) {//判断封面路径是否存在
image.src = path;//设置图片路径
image.setAttribute('crossOrigin', 'anonymous')//设置图片跨域
image.onload = function () {//图片加载完成后执行
let color = colorThief.getColor(image);//获取图片主色调
//设置主题色,下面的颜色变量名根据自己定义的主题变量名来设置
root.style.setProperty("--bieyinan-bar-background", value);
root.style.setProperty("--bieyinan-main", value);
root.style.setProperty("--bieyinan-theme-op-deep", `rgb(${color[0]}, ${color[1]}, ${color[2]},0.6)`);
}
}
}

coverColor();//调用函数

不得不说,这个插件还是很好用的,现在也支持了webp格式的图片。