How to get color value from gradient by percentage with javascript?

本小妞迷上赌 提交于 2019-11-28 21:29:13
passatgt

I was able to solve this issue using this function, which is based on the less.js function: http://lesscss.org/functions/#color-operations-mix

function pickHex(color1, color2, weight) {
    var w1 = weight;
    var w2 = 1 - w1;
    var rgb = [Math.round(color1[0] * w1 + color2[0] * w2),
        Math.round(color1[1] * w1 + color2[1] * w2),
        Math.round(color1[2] * w1 + color2[2] * w2)];
    return rgb;
}

I just simply need to pass the two closest color codes from the gradient array and the ratio where the slider handle is located(which can be calculated easily with the help of the slider width). Here is the live example:

http://jsfiddle.net/vksn3yLL/

may be off topic but I find it could help the ones coming here because they want a relationship between a color and a percentage in jquery .css()

This exemple make a percentage number appear red to green depending if it's closest to zero or 100:

$('#elm').css({color: 'rgb(' + ((100 - percent) *2.56) +',' + (percent *2.56) +',0)'})

Please see demo below:

$('button').click( e => {
  const percent = Math.floor(Math.random()*100);
  const newElm = $(`<b>${percent}</b><br>`)
  .css({color: `rgb(${(100 - percent) *2.56},${percent *2.56},0)`})
  $('body').append(newElm);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click to make new percentage</button><br>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!