I'm trying to create a continuous color transition like the one in Windows 8 installation, We're getting your PC ready.
I couldn't figure out how to write the shift
function. Checking all R, G, B values and matching the current color to the next color.
Can anyone help me on this? Or let me know if there's a better approach to it than this?
function switchColor(id) {
var elm = document.getElementById(id);
// getting elm's current rgb values
var elmColor = window.getComputedStyle(elm).getPropertyValue("background");
var startIndex = elmColor.indexOf("(");
var finishIndex = elmColor.indexOf(")");
var elmRGB = elmColor.substring(startIndex + 1, finishIndex);
var currentColor = elmRGB.split(",");
for (var i = 0; i<3; i++) { currentColor[i] = currentColor[i].trim(); }
// generating a random color => [r, g, ,b]
var nextColor = [];
for (var i = 0; i < 3; i++) {
nextColor[i] = Math.floor(Math.random()*250);
}
// function to convert rgb array to hex color => [r, g, b] = #rgb
function rgbToHex(clr) {
var rgb = clr;
var hex;
var hex1 = rgb[0].toString(16);
var hex2 = rgb[1].toString(16);
var hex3 = rgb[2].toString(16);
if (hex1.length < 2) { hex1 = "0" + hex1; }
if (hex2.length < 2) { hex2 = "0" + hex2; }
if (hex3.length < 2) { hex3 = "0" + hex3; }
return hex = "#" + hex1 + hex2 + hex3;
}
// checking if nextColor rgb values are greater than current rgb's
// so we can increase or decrease for smooth transition
var status = [];
for (var i = 0; i < 3; i++) {
if (nextColor[i] > currentColor[i]) { status.push(1); }
else { status.push(0); }
}
// this isn't part of the code, just testing
elm.style.background = rgbToHex(nextColor);
function shift() {
// shift between colors
// modify currentColor's rgb values and apply it to the elm
// elm.style.background = rgbToHex(currentColor);
}
var handler = setInterval(shift, 100);
}
setInterval(function() { switchColor("sandbox"); }, 2000);
JSFiddle
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…