简体   繁体   中英

changing color in terms of gradient html5 canvas

图1

I have a background that I want to be a solid color, but the color changes as time progresses.

  • The color should be (2,254,253) when the project starts.
  • It should end in (2,120,253) when the project ends.
  • And all the colors in between as project progresses.

This one is easy to do because the only thing I have to change here is how much green to add.

But how can I do this with any 2 color?

This change is just a linear change.

So given two colours

var rgb1 = [100,200,10];
var rgb2 = [200,10,100];

The colour at a time t which is in the range 0 to 1

var colour = [
    ((rgb2[0] - rgb1[0]) * t + rgb1[0]) | 0, // the | 0  floors the value
    ((rgb2[1] - rgb1[1]) * t + rgb1[1]) | 0,
    ((rgb2[2] - rgb1[2]) * t + rgb1[2]) | 0,
]

If you have an absolute time in ms you can convert to normalised t (0-1) as follows

// do at start of time
startTime = performance.now();
endTime =  performance.now() + 10000;  // in ten seconds

// for each update
t = (performance.now() - startTime) / (endTime - startTime);
t = t > 1 ? 1 : t; // make sure you dont go past the end

// get the color
var colour = [
    ((rgb2[0] - rgb1[0]) * t + rgb1[0]) | 0, // the | 0  floors the value
    ((rgb2[1] - rgb1[1]) * t + rgb1[1]) | 0,
    ((rgb2[2] - rgb1[2]) * t + rgb1[2]) | 0,
]

// as a CSS colour
var cssColour = "rgb(" + colour[0] + "," + colour[1] + "," + colour[2] + ")";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM