How to increment / decrement hex color values with javascript / jQuery

前端 未结 3 1263
说谎
说谎 2021-02-06 07:33

Is it possible to increment or decrement hex color values on a step-by-step basis in jQuery / javascript?

What I would like to do is something like this:

Adapt

3条回答
  •  我在风中等你
    2021-02-06 08:07

    I wrote a gradient-function some time ago, maybe it helps you (returns an Array):

    function gradient(startColor, endColor, steps) {
                 var start = {
                         'Hex'   : startColor,
                         'R'     : parseInt(startColor.slice(1,3), 16),
                         'G'     : parseInt(startColor.slice(3,5), 16),
                         'B'     : parseInt(startColor.slice(5,7), 16)
                 }
                 var end = {
                         'Hex'   : endColor,
                         'R'     : parseInt(endColor.slice(1,3), 16),
                         'G'     : parseInt(endColor.slice(3,5), 16),
                         'B'     : parseInt(endColor.slice(5,7), 16)
                 }
                 diffR = end['R'] - start['R'];
                 diffG = end['G'] - start['G'];
                 diffB = end['B'] - start['B'];
    
                 stepsHex  = new Array();
                 stepsR    = new Array();
                 stepsG    = new Array();
                 stepsB    = new Array();
    
                 for(var i = 0; i <= steps; i++) {
                         stepsR[i] = start['R'] + ((diffR / steps) * i);
                         stepsG[i] = start['G'] + ((diffG / steps) * i);
                         stepsB[i] = start['B'] + ((diffB / steps) * i);
                         stepsHex[i] = '#' + Math.round(stepsR[i]).toString(16) + '' + Math.round(stepsG[i]).toString(16) + '' + Math.round(stepsB[i]).toString(16);
                 }
                 return stepsHex;
    
             }
    

提交回复
热议问题