Calculate color HEX having 2 colors and percent/position

前端 未结 4 482
野性不改
野性不改 2020-12-25 13:52

Is it possible to calculate a color in a middle of a gradient?

var color1 = \'FF0000\';
var color2 = \'00FF00\';

// 50% between the two colors, should retur         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-25 14:40

    An ES6 version with comprehensions:

    function interpolateColor(c0, c1, f){
        c0 = c0.match(/.{1,2}/g).map((oct)=>parseInt(oct, 16) * (1-f))
        c1 = c1.match(/.{1,2}/g).map((oct)=>parseInt(oct, 16) * f)
        let ci = [0,1,2].map(i => Math.min(Math.round(c0[i]+c1[i]), 255))
        return ci.reduce((a,v) => ((a << 8) + v), 0).toString(16).padStart(6, "0")
    }
    

    As in the accepted answer, c0,c1 are color codes (without the leading #) and f is "progress" between the two values. (At f=0 this ends up returning c0, at f=1 this returns c1).

    • The first two lines convert the color codes into arrays of scaled integers
    • The third line:
      • "zips" the two integer arrays
      • sums the corresponding values
      • rounds the sum and clamps it to 0-255
    • The fourth line:
      • converts the integer array into a single integer (reduce and bitshifting)
      • converts the integer into its hexadecimal string form
      • ensures the resulting string is 6 characters long and returns it

提交回复
热议问题