博客相关 | 如何提取图片主题色并自动选择标题字体颜色

2022-03-30 15:31:45 浏览数 (1)

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

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

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

处理配色js如下:

代码语言:javascript复制
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://juejin.cn/post/6844903511956815885
  • https://blog.realwds.com/posts/84339efc.html

0 人点赞