如何使用 javascript/jQuery 增加/减少十六进制颜色值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12934720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:28:41  来源:igfitidea点击:

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

javascriptjquerycolorssvgcoloranimation

提问by TimG

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

是否可以在 jQuery / javascript 中逐步增加或减少十六进制颜色值?

What I would like to do is something like this:

我想做的是这样的:

Adapting from a for-loop like

适应 for 循环之类的

for (var i = 0; i <= 100; i++) {
    console.log(i);
}

I would like to do something like

我想做类似的事情

for (var color = 000000; color <= ffffff; color++) {
    console.log(color);
}

without any conversion.

没有任何转换。

Is that possible? I've allready tried this:

那可能吗?我已经试过了:

for (var color = parseInt('000000', 16); color <= parseInt('ffffff', 16); color++){
    console.log(color.toString(16));
}

and it works but it's terribly slow (I get the warning that the script is slowing down the website and if I want to stop the script).

它可以工作,但速度非常慢(我收到警告说脚本正在减慢网站速度,如果我想停止脚本)。

The reason why I want to do this: I would like to change the color stops of svg gradients in a certain interval. If I had for example this svg (simplified):

我想这样做的原因是:我想在某个时间间隔内更改 svg 渐变的色标。例如,如果我有这个 svg(简化):

<svg>
    ...
    <linearGradient>
        <stop offset="0%"  stop-color="#C8E3EF"/>
        <stop offset="100%"  stop-color="#C8E3EF"/>
    </linearGradient>
    ...
</svg>

This gradient would of course appear as a solid color. Now I want to change it step by step to for example

这种渐变当然会显示为纯色。现在我想一步一步地改变它,例如

<svg>
    ...
    <linearGradient>
        <stop offset="0%"  stop-color="#dfcf99"/>
        <stop offset="100%"  stop-color="#c5b6ec"/>
    </linearGradient>
    ...
</svg>

At each step or interval I want to go one value closer to the target color (through addition/substraction). In the end the result should be a smooth color-animation. Is that possible without the conversion? It does not have to be a for-loop btw., I just chose it to illustrate my idea.

在每一步或每一个间隔,我想要一个更接近目标颜色的值(通过加法/减法)。最后的结果应该是一个平滑的颜色动画。没有转换这可能吗?顺便说一句,它不一定是 for 循环,我只是选择它来说明我的想法。

回答by John Doe

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;

         }

回答by Code-Source

Well you can do it simply by this way:

那么你可以通过这种方式简单地做到这一点:

var incrementColor = function(color, step){
    var colorToInt = parseInt(color.substr(1), 16),                     // Convert HEX color to integer
        nstep = parseInt(step);                                         // Convert step to integer
    if(!isNaN(colorToInt) && !isNaN(nstep)){                            // Make sure that color has been converted to integer
        colorToInt += nstep;                                            // Increment integer with step
        var ncolor = colorToInt.toString(16);                           // Convert back integer to HEX
        ncolor = '#' + (new Array(7-ncolor.length).join(0)) + ncolor;   // Left pad "0" to make HEX look like a color
        if(/^#[0-9a-f]{6}$/i.test(ncolor)){                             // Make sure that HEX is a valid color
            return ncolor;
        }
    }
    return color;
};

For steps:

对于步骤:

  • 1 by 1 to 256 increment last color
  • 256 by 256 increment middle color
  • 65536 by 65536 increment first color
  • 1 x 1 到 256 增量最后一种颜色
  • 256 x 256 增量中间色
  • 65536 x 65536 增量第一种颜色

A running example here: http://jsfiddle.net/a3JbB/

这里有一个运行示例:http: //jsfiddle.net/a3JbB/

回答by Anoop

Use setInterval to remove exception(stack overflow). jsfiddle

使用 setInterval 删除异常(堆栈溢出)。提琴手

 var start = 0x000000,
    end = 0xFFFFFF, temp;
    var intervalId = setInterval(function(){
       if(start== end){clearInterval(intervalId )};
       temp = (start).toString(16);                  
             if(temp.length < 8){

                 temp = "0000000".substring(0, 8-temp.length)+temp; 
             } 
                       start++;
            console.log(temp ); 
     }, 10);