美文网首页
Tampermonkey油猴用户脚本获取当前页面的主色值

Tampermonkey油猴用户脚本获取当前页面的主色值

作者: Vagabond_H | 来源:发表于2020-01-21 17:51 被阅读0次
示例

基本用法

  • tampermonkey.net可在官网或chrome webstore中下载安装油猴插件
  • 点击Dashboard进入管理页面


    image
  • 点击+创建新脚本


    image
  • 直接在自执行函数里面写js代码就好了


    image

开头的一些特殊的注释

image

代码

// ==UserScript==
// @name         获取当前页主体颜色
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        http*://*/*
// @grant        none
// @require      https://code.jquery.com/jquery-2.1.4.min.js
// @require      http://html2canvas.hertzen.com/dist/html2canvas.min.js
// ==/UserScript==

(function () {
  'use strict';
  // 常量
  const EFFECTIVE_COUNT = 200;

  /**
   * utils
   */
  // 获取颜色
  const getPixelColor = (r, g, b) => {
    let rHex = r.toString(16);
    r < 16 && (rHex = "0" + rHex);
    let gHex = g.toString(16);
    g < 16 && (gHex = "0" + gHex);
    let bHex = b.toString(16);
    b < 16 && (bHex = "0" + bHex);

    return {
      hexColor: '#' + rHex + gHex + bHex,
      rgbColor: `rgb(${r}, ${g}, ${b})`
    }
  }
  // 复制到剪切板
  const copyText = (text) => {
    if ($(".__temp-input__").length === 0) {
      let input = $("<input>").addClass("__temp-input__");
      $('body').append(input);
    }
    $(".__temp-input__").val(text);
    $(".__temp-input__").select();
    if (document.execCommand) {
      document.execCommand('copy');
    }
  }
  // 下载canvas截屏
  const download = (url) => {
    let aElement = $("<a>").attr({
      'href': url,
      "download": "downImg"
    });
    aElement[0].click();
  }

  // 调用方法的button & 所有样式
  const GlobalStyle = `
  .__fix-btn__ {
    position: fixed;
    left: 20px;
    top: 20px;
    z-index: 10000;
    font-size: 16px;
    opacity: 0.6;
    cursor: pointer;
    background: #1e1f26;
    color: #fff;
    border: none;
    padding: 10px 25px;
    cursor: pointer;
  }
  .__fix-btn__:hover {
    opacity: 1;
  }
  .__fix-btn__:active {
    opacity: 0.8;
  }
  .__temp-input__ {
    position: fixed;
    left: -1000px;
  }
  .__mask__ {
    position: fixed;
    background: rgba(0,0,0,.2);
    height: 100%;
    width: 100%;
    right: 0;
    top: 0;
    z-index: 100001;
    font-size: 16px;
  }
  .__panel__ {
    position: fixed;
    height: 100%;
    width: 600px;
    color: #fff;
    background-color: #1e1f26;
    right: 0;
    top: 0;
    padding: 15px;
    overflow-y: auto;
    z-index: 100002;
  }
  .__panel-list__ {
    display: flex;
  }
  .__panel-item__ {
    height: 60px;
    margin-top: 10px;
    display: flex;
    align-items: center;
    /* justify-content: space-between; */
  }
  .__panel-item-count__ {
    margin-right: 15px;
    text-align: center;
    width: 50px;
    overflow: hidden;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .__panel-item-color__:before {
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    width: 100%;
    border-image: linear-gradient(#8EC5FC, #E0C3FC) 30 30;
  }
  .__panel-item-color__ {
    height: 40px;
    width: 40px;
    margin-right: 20px;
    border-radius: 8px;
    border: 2px solid #8EC5FC;
  }
  .__panel-item-text__ > div {
    color: #bbb;
    transition: all 0.3s;
    cursor: pointer;
  }
  .__panel-item-text__ > div:hover {
    color: #fff;
    /* transform: scale(1.1); */
  }
  `;

  let fixButton = $("<button>").addClass('__fix-btn__').text("获取当前页主体颜色");
  let styleDom = $("<style>").html(GlobalStyle);

  // 有效色值展示

  let mask = $("<div>").addClass("__mask__");
  mask.css('display', 'none');
  mask.click((e) => {
    let target = e.target;
    // 点击到了mask
    if ($(target).hasClass("__mask__")) {
      mask.fadeOut();
    }
    // 点击到了色值
    if ($(target).attr("copyable")) {
      copyText($(target).text());
    }
  })

  $("html").append(styleDom, fixButton, mask);

  // key:色值,  value:色值数
  const hash = {};
  const effectiveColor = [];

  const showEffectiveColor = () => {
    let panel = $("<div>").addClass("__panel__");
    panel.append($("<div>").text("点击色值可复制到剪切板").css("font-size", "12px"));
    // repeat panelItem
    effectiveColor.forEach(item => {
      // 根据r, g, b的值获取hexColor和rgbColor
      let color = getPixelColor(...item[0].split(',').map(o => parseInt(o)));
      let panelItem = $("<div>").addClass("__panel-item__");
      let panelItemCount = $("<div>").text(item[1]).addClass("__panel-item-count__").attr("title", item[1]);
      let panelItemColor = $("<div>").addClass("__panel-item-color__").css('background-color', color.hexColor);
      let panelItemText = $("<div>").addClass("__panel-item-text__");
      panelItemText.append($("<div>").attr('copyable', true).text(color.hexColor));
      panelItemText.append($("<div>").attr('copyable', true).text(color.rgbColor));
      panelItem.append(panelItemCount, panelItemColor, panelItemText);
      panel.append(panelItem);
    })
    mask.empty();
    mask.append(panel);
    mask.fadeIn();
  }

  fixButton.click(() => {
    html2canvas(document.querySelector("html")).then(canvas => {
      const ctx = canvas.getContext("2d");
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      let data = imageData.data;

      // 根据imageData得到所有像素点的色值
      console.time();
      for (let i = 0; i < data.length / 4; i++) {
        let r, g, b, a;
        r = data[i * 4];
        g = data[i * 4 + 1];
        b = data[i * 4 + 2];

        let rgbColor = `${r},${g},${b}`
        if (hash[rgbColor] === undefined) {
          hash[rgbColor] = 1;
        } else {
          hash[rgbColor] += 1;
        }
      }
      console.timeEnd();

      // EFFECTIVE_COUNT个像素点以上,视为有效色值
      effectiveColor.length = 0;
      for (let k in hash) {
        let value = hash[k];
        if (value >= EFFECTIVE_COUNT) {
          effectiveColor.push([k, value]);
        }
      }
      effectiveColor.sort((a, b) => {
        return b[1] - a[1];
      })
      showEffectiveColor();
      // let base64 = canvas.toDataURL('image/png');
      // download(base64);
    });
  });
})();

效果

image

相关文章

网友评论

      本文标题:Tampermonkey油猴用户脚本获取当前页面的主色值

      本文链接:https://www.haomeiwen.com/subject/vibezctx.html