Home > Article > Web Front-end > How to implement color gradient in javascript_javascript skills
Gradient is an important formal beauty rule in aesthetics, and its counterpart is mutation. Shape, size, position, direction, color and other visual factors can be gradient. In color, hue, brightness, and purity can also produce a gradient effect and show a rich layer of beauty. This article mainly describes the gradient algorithm of RGB values of two colors.
Known: A=50, B=200, A and B are divided equally into 3 parts (Step=3), find the value of each part (StepN).
Formula: Gradient = A (B-A) / Step * N
Note] In order to improve efficiency and avoid floating point operations when programming, division is often placed at the end, so the formula becomes: Gradient = A (B-A) * N / Step
When Step=3, according to the formula, Step1=A (A-B)/3*1=50 (200-50)/3=100, Step2=A (A-B)/3*2=50 (200- 50)/3*2=150. This is the algorithm principle of uniform gradient. It is very simple, elementary school knowledge.
The gradient of two colors is to calculate the RGB channels of the two colors respectively. For example, the two colors are RGB(200,50,0) and RGB(50,200,0). Calculate using the above formula. :
RStep1=RA=RA (BA-RA)/Step*N=200 (50-200)/3*1=200-50=150
GStep1=GA=GA (GA-GA)/Step*N=50 (200-50)/3*1=50 50=100
BStep1=BA=BA (BA-BA)/Step*N=0
So RGBStep1=(150,100,0), the same method can be used to find RGBStep2=(100,150,0).
This is how the gradient text effects in web pages are created. For example, there is such a code in the HTML of your web page: You are the most beautiful rainbow in my sky. Add the following code at the end to achieve gradient text. (Two colors to generate the gradient: #c597ff and #73e7a9)
// Convert color #FF00FF format to Array(255,0,255)
function color2rgb(color)
{
var r = parseInt(color.substr(1, 2), 16);
var g = parseInt(color.substr(3, 2), 16);
var b = parseInt(color.substr(5, 2), 16);
return new Array(r, g, b);
}
//The color Array(255,0,255) format is converted to #FF00FF
function rgb2color(rgb)
{
var s = "#";
for (var i = 0; i < 3; i )
{
var c = Math.round(rgb[i]).toString(16);
if (c.length == 1)
c = '0 ' c;
s = c;
}
return s.toUpperCase();
}
//Generate gradient
function gradient()
{
var str = myText.innerText;
var result = "";
var Step = str.length - 1;
var Gradient = new Array(3);
var A = color2rgb(ColorA);
var B = color2rgb(ColorB);
for (var N = 0; N <= Step; N )
{
for (var c = 0; c < 3; c ) // RGB channels are calculated separately
{
Gradient[c] = A[c] (B[c]-A[c]) / Step * N;
}
result = "" str.charAt(N) "";
}
myText.innerHTML = result;
}
gradient(); // Run program
For gradients of three or more colors A, B, and C, theoretically, you only need to gradient A and B first, then gradient B and C, and so on. In practice, in order to make the color distribution of each pixel of the gradient even, a variety of interpolation algorithms have been produced. The specific algorithms will be discussed later.