Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/411.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript颜色渐变_Javascript_Colors_Gradient_Rgb - Fatal编程技术网

Javascript颜色渐变

Javascript颜色渐变,javascript,colors,gradient,rgb,Javascript,Colors,Gradient,Rgb,使用带有或不带Jquery的javascript,我需要根据开始和结束颜色创建颜色渐变。这可以通过编程实现吗 最后的颜色只会比开始的颜色更深,这是一个无序的列表,我无法控制li项目的数量。我正在寻找一种解决方案,允许我选择一个开始和结束颜色,将十六进制值转换为RGB,以便可以在代码中进行操作。起始RGB值将根据项目数计算的步长值递增 因此,如果列表有8个项目,则需要在8个步骤中增加单独的红、绿、蓝值,以获得最终颜色。有更好的方法吗?如果有,我在哪里可以找到一些示例代码 是的,绝对是 我用Java

使用带有或不带Jquery的javascript,我需要根据开始和结束颜色创建颜色渐变。这可以通过编程实现吗

最后的颜色只会比开始的颜色更深,这是一个无序的列表,我无法控制li项目的数量。我正在寻找一种解决方案,允许我选择一个开始和结束颜色,将十六进制值转换为RGB,以便可以在代码中进行操作。起始RGB值将根据项目数计算的步长值递增

因此,如果列表有8个项目,则需要在8个步骤中增加单独的红、绿、蓝值,以获得最终颜色。有更好的方法吗?如果有,我在哪里可以找到一些示例代码

是的,绝对是

我用Java做这件事,用JavaScript也应该相当简单

首先,您需要将颜色分解为RGB组件

然后计算组件的开始和结束之间的差异

最后,计算百分比差异并乘以每个组件的开始颜色,然后将其添加到开始颜色

假设您可以获得RGB值,这应该可以做到:

var diffRed = endColor.red - startColor.red;
var diffGreen = endColor.green - startColor.green;
var diffBlue = endColor.blue - startColor.blue;

diffRed = (diffRed * percentFade) + startColor.red;
diffGreen = (diffGreen * percentFade) + startColor.green;
diffBlue = (diffBlue * percentFade) + startColor.blue;

“percentFade”是一个浮动小数,表示淡入“endColor”的距离。1将是完全褪色(从而创建结束颜色)。0将是无褪色(起始颜色)。

您可以检索元素列表。我不熟悉jQuery,但是prototypejs有Element.childElements(),它将返回一个数组。一旦知道阵列的长度,就可以确定每一步要更改多少像素组件。下面的一些代码我还没有在我展示的表单中测试过,但希望它能给你一个想法

function hex (c) {
  var s = "0123456789abcdef";
  var i = parseInt (c);
  if (i == 0 || isNaN (c))
    return "00";
  i = Math.round (Math.min (Math.max (0, i), 255));
  return s.charAt ((i - i % 16) / 16) + s.charAt (i % 16);
}

/* Convert an RGB triplet to a hex string */
function convertToHex (rgb) {
  return hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
}

/* Remove '#' in color hex string */
function trim (s) { return (s.charAt(0) == '#') ? s.substring(1, 7) : s }

/* Convert a hex string to an RGB triplet */
function convertToRGB (hex) {
  var color[];
  color[0] = parseInt ((trim(hex)).substring (0, 2), 16);
  color[1] = parseInt ((trim(hex)).substring (2, 4), 16);
  color[2] = parseInt ((trim(hex)).substring (4, 6), 16);
}


/* The start of your code. */
var start = convertToRGB ('#000000');    /* The beginning of your gradient */
var end   = convertToRGB ('#ffffff');    /* The end of your gradient */
var arr = $('.gradientList').childElements();
var len = arr.length();                  /* The number of colors to compute */
var alpha = 0.5;                         /* Alpha blending amount */

for (i = 0; i < len; i++) {
    var c = [];

    c[0] = start[0] * alpha + (1 - alpha) * end[0];
    c[1] = start[1] * alpha + (1 - alpha) * end[1];
    c[2] = start[2] * alpha + (1 - alpha) * end[2];

    /* Set the background color of this element */
    arr[i].setStyle ({ 'background-color': convertToHex (c) });
}
函数十六进制(c){ var s=“0123456789abcdef”; var i=parseInt(c); 如果(i==0 | | isNaN(c)) 返回“00”; i=Math.round(Math.min(Math.max(0,i),255)); 返回s.charAt((i-i%16)/16)+s.charAt(i%16); } /*将RGB三元组转换为十六进制字符串*/ 函数convertToHex(rgb){ 返回十六进制(rgb[0])+十六进制(rgb[1])+十六进制(rgb[2]); } /*删除颜色十六进制字符串中的“#”*/ 函数修剪{return(s.charAt(0)='#')?s.substring(1,7):s} /*将十六进制字符串转换为RGB三元组*/ 函数转换器GB(十六进制){ var颜色[]; 颜色[0]=parseInt((trim(hex))。子字符串(0,2),16); 颜色[1]=parseInt((trim(hex))。子字符串(2,4),16); 颜色[2]=parseInt((trim(hex))。子字符串(4,6,16); } /*代码的开头*/ var start=convertorGB('#000000');/*渐变的开始*/ var end=转换器GB('#ffffff');/*你的梯度结束了*/ var arr=$('.gradientList').childElements(); var len=阵列长度();/*要计算的颜色数*/ varα=0.5;/*α混合量*/ 对于(i=0;i我创建了一个JS库来解决这个一般问题。您只需使用
setNumberRange
设置项目数量,并使用
setSpectrum
设置开始和结束颜色。然后使用
colorat
获得十六进制颜色代码

var numberOfItems = 8;
var rainbow = new Rainbow(); 
rainbow.setNumberRange(1, numberOfItems);
rainbow.setSpectrum('red', 'black');
var s = '';
for (var i = 1; i <= numberOfItems; i++) {
    var hexColour = rainbow.colourAt(i);
    s += '#' + hexColour + ', ';
}
document.write(s); 
// gives:
// #ff0000, #db0000, #b60000, #920000, #6d0000, #490000, #240000, #000000, 
var numberOfItems=8;
var rainbow=新彩虹();
rainbow.SetNumberArrange(1,numberOfItems);
彩虹光谱(“红色”、“黑色”);
var s='';

对于(var i=1;i不是很强大,但在大多数情况下都可以工作,并且除了jQuery之外,您不必为以下代码包含任何其他库:

HTML:


JavaScript:

function rainbow(value, s, l, max, min, start, end) {
    value = ((value - min) * (start - end) / max)+end;
    return 'hsl(' + value + ','+s+'%,'+l+'%)';
}

function createRainbowDiv(start,end){
    var gradient = $("<div>").css({display:"flex", "flex-direction":"row",height:"100%"});
    for (var i = start; ((i <= end) && (i >= start)) || ((i >= end) && (i <= start)); 
        i += (end-start) / Math.abs(end-start)){
            gradient.append($("<div>").css({float:"left","background-color":rainbow(i, 100,50, Math.max(start,end), Math.min(start,end), start,end),flex:1}));
    }

    return gradient;
}

$("#colors").append(createRainbowDiv(0,150));
$("#colors").css("width","100%").css("height","10px");
函数彩虹(值、s、l、最大值、最小值、开始值、结束值){ 值=((值-最小值)*(开始-结束)/最大值)+结束; 返回'hsl('+value+'、'+s+'%、'+l+'%)'; } 函数createRainbowDiv(开始、结束){ var gradient=$(“”).css({display:“flex”,“flex direction:“row”,height:“100%”);
对于(var i=start;((i=start))| |((i>=end)和&(i我基于@desau-answer使用此函数:

 getGradientColor = function(start_color, end_color, percent) {
   // strip the leading # if it's there
   start_color = start_color.replace(/^\s*#|\s*$/g, '');
   end_color = end_color.replace(/^\s*#|\s*$/g, '');

   // convert 3 char codes --> 6, e.g. `E0F` --> `EE00FF`
   if(start_color.length == 3){
     start_color = start_color.replace(/(.)/g, '$1$1');
   }

   if(end_color.length == 3){
     end_color = end_color.replace(/(.)/g, '$1$1');
   }

   // get colors
   var start_red = parseInt(start_color.substr(0, 2), 16),
       start_green = parseInt(start_color.substr(2, 2), 16),
       start_blue = parseInt(start_color.substr(4, 2), 16);

   var end_red = parseInt(end_color.substr(0, 2), 16),
       end_green = parseInt(end_color.substr(2, 2), 16),
       end_blue = parseInt(end_color.substr(4, 2), 16);

   // calculate new color
   var diff_red = end_red - start_red;
   var diff_green = end_green - start_green;
   var diff_blue = end_blue - start_blue;

   diff_red = ( (diff_red * percent) + start_red ).toString(16).split('.')[0];
   diff_green = ( (diff_green * percent) + start_green ).toString(16).split('.')[0];
   diff_blue = ( (diff_blue * percent) + start_blue ).toString(16).split('.')[0];

   // ensure 2 digits by color
   if( diff_red.length == 1 ) diff_red = '0' + diff_red
   if( diff_green.length == 1 ) diff_green = '0' + diff_green
   if( diff_blue.length == 1 ) diff_blue = '0' + diff_blue

   return '#' + diff_red + diff_green + diff_blue;
 };
例如:

getGradientColor('#FF0000', '#00FF00', 0.4);
=> "#996600"

生成颜色数组的正确函数!

函数十六进制(c){ var s=“0123456789abcdef”; var i=parseInt(c); 如果(i==0 | | isNaN(c)) 返回“00”; i=Math.round(Math.min(Math.max(0,i),255)); 返回s.charAt((i-i%16)/16)+s.charAt(i%16); } /*将RGB三元组转换为十六进制字符串*/ 函数convertToHex(rgb){ 返回十六进制(rgb[0])+十六进制(rgb[1])+十六进制(rgb[2]); } /*删除颜色十六进制字符串中的“#”*/ 函数修剪{return(s.charAt(0)='#')?s.substring(1,7):s} /*将十六进制字符串转换为RGB三元组*/ 函数转换器GB(十六进制){ var color=[]; 颜色[0]=parseInt((trim(hex))。子字符串(0,2),16); 颜色[1]=parseInt((trim(hex))。子字符串(2,4),16); 颜色[2]=parseInt((trim(hex))。子字符串(4,6,16); 返回颜色; } 函数generateColor(colorStart、colorEnd、colorCount){ //渐变的开始 var start=CONVERTORGB(colorStart); //你的梯度结束了 var end=转换器GB(colorEnd); //要计算的颜色数 var len=颜色计数; //α混合量 varα=0.0; var saida=[]; 对于(i=0;i

我需要为未知集合创建足够大的颜色选项数组
getGradientColor('#FF0000', '#00FF00', 0.4);
=> "#996600"
    <style>
      #test {
          width:200px;
          height:100px;
          border:solid 1px #000;
      }

      .test {
          width:49%;
          height:100px;
          border:solid 1px #000;
          display: inline-block;
      }
    </style>
</head>
<body>

<div id="test"></div>

<div class="test"></div>

<div class="test"></div>

<div class="test"></div>

<div class="test"></div>

<div class="test"></div>

<div class="test"></div>

<div class="test"></div>

<div class="test"></div>

<div class="test"></div>

<div class="test"></div>

    <script>

      var GColor = function(r,g,b) {
          r = (typeof r === 'undefined')?0:r;
          g = (typeof g === 'undefined')?0:g;
          b = (typeof b === 'undefined')?0:b;
          return {r:r, g:g, b:b};
      };


      // increases each channel by the difference of the two
      // divided by 255 (the number of colors stored in the range array)
      // but only stores a whole number
      // This should respect any rgb combinations
      // for start and end colors

      var createColorRange = function(c1) {
          var colorList = [], tmpColor, rr = 0, gg = 0, bb = 0;
          for (var i=0; i<255; i++) {
            tmpColor = new GColor();
              if (rExp >= 0) {

                tmpColor.r = Math.floor(c1.r - rr);
                rr += rAdditive;

              } else {

                tmpColor.r = Math.floor(c1.r + rr);
                rr += rAdditive;
              }

              if (gExp >= 0) {

                tmpColor.g = Math.floor(c1.g - gg);
                gg += gAdditive;

              } else {

                tmpColor.g = Math.floor(c1.g + gg);
                gg += gAdditive;
              }

              if (bExp >= 0) {

                tmpColor.b = Math.floor(c1.b - bb);
                bb += bAdditive;

              } else {

                tmpColor.b = Math.floor(c1.b + bb);
                bb += bAdditive;

              }

              console.log(tmpColor);


              colorList.push(tmpColor);
          }
          return colorList;
      };

      /* ==================
         Testing Code Below
         ================== */


      var firstColor = new GColor(255, 24, 0);
      var secondColor = new GColor(255, 182, 0);

      // Determine the difference
      var rExp = firstColor.r - secondColor.r;

      // Divide that difference by length of the array
      // you would like to create (255 in this case)
      var rAdditive = Math.abs(rExp)/255;

      var gExp = firstColor.g - secondColor.g;
      var gAdditive = Math.abs(gExp)/255;

      var bExp = firstColor.b - secondColor.b;
      var bAdditive = Math.abs(bExp)/255;

      var range = createColorRange(firstColor, secondColor);
      console.log(range);
      var pointer = 0;


      // This gently cycles through
      // all the colors on a single element
      function rotateColors() {
          var currentColor = range[pointer];
          document.getElementById("test").style.backgroundColor = "rgb("+currentColor.r+","+currentColor.g+","+currentColor.b+")";
          pointer++;
          if (pointer < range.length) window.setTimeout(rotateColors, 5);
      }

       rotateColors();

      // say I have 5 elements
      // so I need 5 colors
      // I already have my first and last colors
      // but I need to locate the colors between
      // my start color and my end color
      // inside of this range
      // so I divide the range's length by the
      // number of colors I need
      // and I store the index values of the middle values

      // those index numbers will then act as my keys to retrieve those values
      // and apply them to my element

      var myColors = {};
      var objects = document.querySelectorAll('.test');
        myColors.num = objects.length;


      var determineColors = function(numOfColors, colorArray) {
        var colors = numOfColors;

        var cRange = colorArray;
        var distance = Math.floor(cRange.length/colors);
        var object = document.querySelectorAll('.test');

        var j = 0;
        for (var i = 0; i < 255; i += distance) {

          if ( (i === (distance*colors)) ) {
            object[j].style.backgroundColor = "rgb(" + range[255].r + ", " + range[255].g + ", " + range[255].b + ")";

            j = 0;
            // console.log(range[i]);
          } else {

                // Apply to color to the element
                 object[j].style.backgroundColor = "rgb(" + range[i].r + ", " + range[i].g + ", " + range[i].b + ")";


                  // Have each element bleed into the next with a gradient
               // object[j].style.background = "linear-gradient( 90deg, rgb(" + range[i].r + ", " + range[i].g + ", " + range[i].b + "), rgb(" + range[i+distance].r + ", " + range[i+distance].g + ", " + range[i+distance].b + "))";

            j++;
          }

        }
      };


      setTimeout( determineColors(myColors.num, range), 2000);

    </script>
</body>
var gradientColors = []
var startColor = "rgb(100,200,50)", endColor = "green"
var start = xolor(startColor)
for(var n=0; n<8; n++) {
   gradientColors.push(start.gradient(endColor, n/8))
}  
Element.prototype.setGradient = function( from, to, vertical ){
   this.style.background = 'linear-gradient(to '+(vertical ? 'top' : 'left')+', '+from+', '+to+' 100%)';
}
document.querySelector('.mydiv').setGradient('red','green');
Element.prototype.setGradient = function( fromColor, toColor ){

    var canvas = document.createElement('canvas');
    var ctx    = canvas.getContext('2d');
    var b      = this.getBoundingClientRect();
    var grd    = ctx.createLinearGradient(0, 0, b.width, 0);

    canvas.width = b.width;
    canvas.height = b.height;

    grd.addColorStop(0, fromColor);
    grd.addColorStop(1, toColor);

    ctx.fillStyle = grd;
    ctx.fillRect(0, 0, b.width, b.height);

    this.style.backgroundImage = 'url('+canvas.toDataURL()+')';
}
document.querySelector('.mydiv').setGradient('red','green');
Element.prototype.setGradient = function( fromColor, toColor, vertical ){

    var canvas = document.createElement('canvas');
    var ctx    = canvas.getContext('2d');
    var b      = this.getBoundingClientRect();
    var grd    = ctx.createLinearGradient(0, 0, vertical ? 0 : b.width, vertical ? b.height : 0);

    canvas.width = b.width;
    canvas.height = b.height;

    grd.addColorStop(0, fromColor);
    grd.addColorStop(1, toColor);

    ctx.fillStyle = grd;
    ctx.fillRect(0, 0, b.width, b.height);

    this.style.backgroundImage = 'url('+canvas.toDataURL()+')';
}
document.querySelector('.mydiv').setGradient('red','green',true);
function coloursBetween(fromColour, toColour, numberOfColours){

    var colours = []; //holds output
    var fromSplit = getRGBAValues(hexToRGBA(fromColour, 1.0)); //get raw values from hex
    var toSplit = getRGBAValues(hexToRGBA(toColour, 1.0));
    
    var fromRed = fromSplit[0]; //the red value as integer
    var fromGreen = fromSplit[1];
    var fromBlue = fromSplit[2];
    
    var toRed = toSplit[0];
    var toGreen = toSplit[1];
    var toBlue = toSplit[2];
    
    var difRed = toRed - fromRed; //difference between the two
    var difGreen = toGreen - fromGreen;
    var difBlue = toBlue - fromBlue;
    
    var incrementPercentage = 1 / (numberOfColours-1); //how much to increment percentage by
    
    for (var n = 0; n < numberOfColours; n++){

        var percentage = n * incrementPercentage; //calculate percentage 
        var red = (difRed * percentage + fromRed).toFixed(0); //round em for legibility
        var green = (difGreen * percentage + fromGreen).toFixed(0);
        var blue = (difBlue * percentage + fromBlue).toFixed(0);
        var colour = 'rgba(' + red + ',' + green + ',' + blue + ',1)'; //create string literal
        colours.push(colour); //push home
        
    }
    
    return colours;
}
function getRGBAValues(string) {
    
  var cleaned = string.substring(string.indexOf('(') +1, string.length-1);
  var split = cleaned.split(",");
  var intValues = [];
  for(var index in split){
      intValues.push(parseInt(split[index]));
  }
  return intValues;
}
function hexToRGBA(hex, alpha){
    var c;
    if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
        c= hex.substring(1).split('');
        if(c.length== 3){
            c= [c[0], c[0], c[1], c[1], c[2], c[2]];
        }
        c= '0x'+c.join('');
        return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+','+alpha+')';
    }
    return rgba(0,0,0,1);
    //throw new Error('Bad Hex');
}
var gradientColours = coloursBetween("#FF0000", "#0000FF", 5);