前端取图片相同颜色作为遮罩或者背景

需求

  • 遮罩层取图片相同/相似的颜色作为遮罩

效果

做法

npm库

grade.js

  • 所提供图像中前 2 个主色生成的互补渐变
  • https://github.com/benhowdle89/grade

COLOR THIEF

  • 只需使用Javascript即可从图像中获取调色板。

  • https://github.com/lokesh/color-thief

  • https://lokeshdhakar.com/projects/color-thief

rgbaster.js

  • https://github.com/briangonzalez/rgbaster.js
  • 一个非常简单、零依赖、基于 promise 的 javascript 库,用于从图像(在浏览器中)中提取主要颜色。

算法

  • 基本思路都是获取每一种rgb的出现次数,进行计算分析,如果出现跨域问题还需要后端配合解决

  • https://kuangyx.cn/docs/%E6%96%87%E7%AB%A0/%E5%89%8D%E7%AB%AF/%E6%8F%90%E5%8F%96%E5%9B%BE%E7%89%87%E4%B8%BB%E9%A2%98%E8%89%B2.html

  • 也可以直接使用这位大佬写好的

    • https://github.com/hubingliang/colorfulImg
    • 代码里面的colorfulImg

简单做法

做法1

  • 效果

  • 代码
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 原始图 -->
    <div class="origin"></div>
    <!-- 模糊 -->
    <div class="mask"></div>
    <style>
      div.origin {
        position: relative;
        width: 320px;
        height: 200px;
        overflow: hidden;
        background-repeat: no-repeat;
        background-image: url("https://oss.dreamlove.top/i/2024/02/20/xqsvvg.png");
      }
      div.mask{
        position: relative;
        width: 320px;
        height: 200px;
        overflow: hidden;
        /* 关键代码 */
        background-repeat: no-repeat;
        background-image: url("https://oss.dreamlove.top/i/2024/02/20/xqsvvg.png");
        background-size: 20000%;
        background-position: center;
      }
    </style>
  </body>
</html>

参考文章

  • https://www.cnblogs.com/coco1s/p/14754188.html
  • https://www.zhangxinxu.com/wordpress/2014/08/image-dominant-color-get-rgbaster-js/
  • https://blog.csdn.net/weixin_64388392/article/details/134426851

后话

  • 其实简单做法里面的思路,也可以根据背景来设置字体颜色,大概思路就是字体颜色设置为透明,并利用background-clip进行设置
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

未成年梦想

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值