根据百分比梯度确定颜色

我正在寻找一种根据渐变百分比确定纯色的方法。基本上就像下图一样

https://img1.sycdn.imooc.com/656d8eff00019e1806500304.jpg

我已经使用 CSS 来获取渐变,但我不知道如何从该渐变中选择纯色。这是渐变的 CSS:

background-image: linear-gradient(to bottom, #00b050 20%, #4ac148 40%, #74d13e, #9de031, #c6ee21, #dbe508, #eedb00, #ffd000, #ffad00, #ff8700, #ff5b00, #ff0000);

最坏的情况是,我可以在该渐变上遍历并分配 0-100 之间的 RGB 值并使用它。然而,我忍不住认为必须有更好的编程方式来解决这个问题。

任何帮助都会有用的。


精慕HU
浏览 60回答 2
2回答

墨色风雨

计算两种颜色之间的中间色是如此简单color1=rgb(ar,ag,ab)color2=rgb(br,bg,bb)color=rgb(ar+factor*(br-ar),ag+factor*(bg-ag),ab+factor*(bb-ab))好吧,为了更轻松地计算因子,我们可以创建一系列 div。想象一下你有一个像这样的渐变&nbsp; background-image: linear-gradient(to right,#ff0000,#00ffff);我去创建一系列颜色colors2:any[]=[&nbsp;{color:"#ff0000",porc:0},&nbsp;{color:"#ff0000",porc:0},&nbsp;{color:"#00ffff",porc:100},]看到我用 porc:0 重复了第一个元素并变换添加 r、g、b 属性this.colors2.forEach(c=>{&nbsp; c.r=parseInt(c.color.substr(1,2),16)&nbsp; c.g=parseInt(c.color.substr(3,2),16)&nbsp; c.b=parseInt(c.color.substr(5),16)})所以我可以做一个 *ngFor<div class="col" (mousemove)="mouseMove($event,colors2[i],colors2[i+1])"&nbsp;&nbsp; &nbsp;*ngFor="let color of colors2|slice:0:(colors2.length-1);let i=index"&nbsp; [style.background-image]="'linear-gradient(to right,'+colors2[i].color+','+colors2[i+1].color+')'"&nbsp; [style.width]="(colors2[i+1].porc-colors2[i].porc)+'%'"></div>在哪里.col{&nbsp; height:2rem;&nbsp; display:inline-block}其中函数 mouseMove 计算中间颜色&nbsp; mouseMove(e,color1,color2)&nbsp; {&nbsp; &nbsp; this.margin=e.clientX-14&nbsp; &nbsp; const rect=e.target.getBoundingClientRect();&nbsp; &nbsp; const alfa=(e.clientX - rect.left)/rect.width&nbsp; &nbsp; const r=Math.floor(color1.r+alfa*(color2.r-color1.r)).toString(16)&nbsp; &nbsp; const g=Math.floor(color1.g+alfa*(color2.g-color1.g)).toString(16)&nbsp; &nbsp; const b=Math.floor(color1.b+alfa*(color2.b-color1.b)).toString(16)&nbsp; &nbsp; const color=('00'+r).slice(-2)+('00'+g).slice(-2)+('00'+b).slice(-2)&nbsp; &nbsp; this.result="#"+color&nbsp; }在stackblitz中你可以看到三个渐变。每个渐变都有两个水平 div,一个带有使用 css 渐变的 div,下面是“模拟”div 与几个 div 的组合。如果将鼠标移到最后一个上,您会看到颜色

哔哔one

一种想法是使渐变非常大,然后调整background-position为具有一种颜色或至少近似它:.box {&nbsp; background-image: linear-gradient(to right, #00b050 20%, #4ac148 40%, #74d13e, #9de031, #c6ee21, #dbe508, #eedb00, #ffd000, #ffad00, #ff8700, #ff5b00, #ff0000);&nbsp; background-size:10000% 100%;&nbsp; border:10px solid;&nbsp; width:50px;&nbsp; height:100px;&nbsp; display:inline-block;}<div class="box" style="background-position:20% 0"></div><div class="box" style="background-position:40% 0"></div><div class="box" style="background-position:50% 0"></div><div class="box" style="background-position:60% 0"></div><div class="box" style="background-position:70% 0"></div><div class="box" style="background-position:80% 0"></div><div class="box" style="background-position:100% 0"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5