How to define all colors in a gradient?

Possible duplicate:
Javascript color gradient

I have color one (let yellow) and color two (blue) - they make up the gradient.
Based on a value from 0 to 100, (0 is yellow and 100 is blue), I would like to present a mixture of the colors one and two.

I am trying to do this in a mobile browser (specifically for safari).

Is there any way to do this in javascript?

+4
source share
1 answer

If you are trying to create a color that is some percentage (0-100) between two other colors, you can do this with this javascript:

function makeGradientColor(color1, color2, percent) { var newColor = {}; function makeChannel(a, b) { return(a + Math.round((ba)*(percent/100))); } function makeColorPiece(num) { num = Math.min(num, 255); // not more than 255 num = Math.max(num, 0); // not less than 0 var str = num.toString(16); if (str.length < 2) { str = "0" + str; } return(str); } newColor.r = makeChannel(color1.r, color2.r); newColor.g = makeChannel(color1.g, color2.g); newColor.b = makeChannel(color1.b, color2.b); newColor.cssColor = "#" + makeColorPiece(newColor.r) + makeColorPiece(newColor.g) + makeColorPiece(newColor.b); return(newColor); } 

This function assumes that the gradient is performed with linear interpolation between each r, g, and b value of the channel of the two colors of the end points, so that a 50% gradient value is the middle of each r, g, b value (halfway between the two colors are presented). After this, other types of gradients can be made (with various interpolation functions).

To assign this result to the background, you use the CSS color value, which I added to the return result as follows:

 // sample usage var yellow = {r:255, g:255, b:0}; var blue = {r:0, g:0, b:255}; var newColor = makeGradientColor(yellow, blue, 79); element.style.backgroundColor = newColor.cssColor; 
+19
source

Source: https://habr.com/ru/post/1389343/


All Articles