Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript color gradient

Using javascript with or without Jquery, I need to a create a gradient of colours based on a start and finish color. Is this possible to do programmatically?

The end colour is only ever going to be darker shade of the start colour and it's for an unordered list which I have no control over the number of li items. I'm looking for a solution that allows me to pick a start and end color, convert the hex value into RGB so it can be manipulated in code. The starting RGB values gets incremented by a step value calculated based upon the number of items.

so if the list had 8 items then the it needs to increment the seperate Red Green Blue values in 8 steps to achieve the final colour. Is there a better way to do it and if so where can I find some sample code?

like image 997
Dave Avatar asked Jun 20 '10 18:06

Dave


People also ask

How do you color a gradient in Javascript?

The addColorStop() method specifies the color stops, and its position along the gradient. Gradient positions can be anywhere between 0 to 1. To use the gradient, set the fillStyle or strokeStyle property to the gradient, then draw the shape (rectangle, text, or a line).

How do you create a linear gradient in Javascript?

The linear-gradient() function sets a linear gradient as the background image. To create a linear gradient you must define at least two color stops. Color stops are the colors you want to render smooth transitions among. You can also set a starting point and a direction (or an angle) along with the gradient effect.

How do you find the gradient of a color?

Select the Gradient tool in the toolbar. In the selected artwork you'll see the gradient annotator, which shows the gradient slider and the color stops. Double-click a color stop on the artwork to edit the color, drag the color stops, click beneath the gradient slider to add new color stops, and more.

What is gradient color in HTML?

Gradient Backgrounds. CSS gradients let you display smooth transitions between two or more specified colors. CSS defines three types of gradients: Linear Gradients (goes down/up/left/right/diagonally) Radial Gradients (defined by their center)


2 Answers

I created a JS library, RainbowVis-JS to solve this general problem. You just have to set the number of items using setNumberRange and set the start and end colour using setSpectrum. Then you get the hex colour code with colourAt.

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,  

You are welcome to look at the library's source code. :)

like image 198
anomal Avatar answered Oct 06 '22 16:10

anomal


Correct function to generate array of colors!

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);    return color;  }    function generateColor(colorStart,colorEnd,colorCount){    	// The beginning of your gradient  	var start = convertToRGB (colorStart);        	// The end of your gradient  	var end   = convertToRGB (colorEnd);        	// The number of colors to compute  	var len = colorCount;    	//Alpha blending amount  	var alpha = 0.0;    	var saida = [];  	  	for (i = 0; i < len; i++) {  		var c = [];  		alpha += (1.0/len);  		  		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];    		saida.push(convertToHex (c));  		  	}  	  	return saida;  	  }    // Exemplo de como usar      var tmp = generateColor('#000000','#ff0ff0',10);    for (cor in tmp) {    $('#result_show').append("<div style='padding:8px;color:#FFF;background-color:#"+tmp[cor]+"'>COLOR "+cor+"° - #"+tmp[cor]+"</div>")     }  	
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div id="result_show"></div>
like image 31
Euler Junior Avatar answered Oct 06 '22 16:10

Euler Junior