博客相关 | 如何获取图片主题色并修改字体颜色

今天在写博客的时候,做了一个封面图,然后hexo cl && hexo g && gulp && hexo s一键生成,点开后却发现这个标题的字体颜色亮瞎我的眼睛:

博客相关 | 如何获取图片主题色并修改字体颜色_第1张图片

于是试了很多帖子,终于把它改好了:

博客相关 | 如何获取图片主题色并修改字体颜色_第2张图片

提取主题色的js:https://github.com/briangonzalez/rgbaster.js

处理配色js如下:

if (document.getElementById('post-cover')) {
  const img = document.getElementById('post-cover').getAttribute('data-lazy-src')
  RGBaster.colors(img, {
      paletteSize: 30,
      exclude: ["rgb(255,255,255)", "rgb(0,0,0)", "rgb(254,254,254)"],
      success: function(t) {
        if (t.dominant != 'rgb()'){
          const c = t.dominant.match(/\d+/g);
          const Color = `rgba(${c[0]},${c[1]},${c[2]},0.8)`;
          let fontColor;
          //const grayLevel = c[0] * 0.299 + c[1] * 0.587 + c[2] * 0.114;
          const grayLevel = c[0] * 0.213 + c[1] * 0.715 + c[2] * 0.072;
          //if (grayLevel >= 190) {
          if (grayLevel >= 255/2) {
            // 若为浅色,把文字设置为黑色
            fontColor = '#000';
            metaColor = '#1C1C1C';
          } else {
            fontColor = '#fff';
            metaColor = '#eee';
          }
          document.styleSheets[0].addRule(":root", "--mj-main:" + Color + "!important")
          document.styleSheets[0].addRule(":root", "--mj-titlecolor:" + fontColor + "!important")
          document.styleSheets[0].addRule(":root", "--mj-metacolor:" + metaColor + "!important")
        } else {
          document.styleSheets[0].addRule(":root", "--mj-main: rgba(255,250,240,0.5) !important")
          document.styleSheets[0].addRule(":root", "--mj-titlecolor: #000 !important")
          document.styleSheets[0].addRule(":root", "--mj-metacolor: #1C1C1C !important")
        }
      },
      error: function() {
          document.styleSheets[0].addRule(":root", "--mj-main: rgba(255,250,240,0.5) !important")
          document.styleSheets[0].addRule(":root", "--mj-titlecolor: #000 !important")
          document.styleSheets[0].addRule(":root", "--mj-metacolor: #1C1C1C !important")
      }
  })
} else {
  document.styleSheets[0].addRule(":root", "--mj-main: transparent !important")
  document.styleSheets[0].addRule(":root", "--mj-titlecolor: var(--light-grey) !important")
}

参考:

  • https://blog.justlovesmile.top/posts/b16c0eda.html
  • https://juejin.cn/post/6844903511956815885
  • https://blog.realwds.com/posts/84339efc.html

你可能感兴趣的:(博客相关,代码编程,折腾记录,javascript,前端,开发语言)