简体   繁体   中英

js background colour transition

I've got the following piece of code and I'd like the 'rect' element (which is a canvas element) transition the colour from black to white. It doesn't. Please advise:

var background = document.getElementById("rect");

setInterval(function() {
    for (i=0;i<255;i++) {
        background.style.backgroundColor = 'rgb(' + [i, i, i].join(',') + ')';
    }
}, 900);

By changing the colors in a loop, you're effectively doing it all at once. Instead, do one change per interval callback:

var background = document.getElementById("rect");

var i = 0;
var timer = setInterval(function() {
    background.style.backgroundColor = 'rgb(' + [i, i, i].join(',') + ')';
    if (++i > 255) {
        clearInterval(timer);
    }
}, 900);

Note that at 900ms per change and 255 changes, that will take a long time to complete, so you may need to adjust the interval.

Here's an example using an interval of 20ms:

 var background = document.getElementById("rect"); var i = 0; var timer = setInterval(function() { background.style.backgroundColor = 'rgb(' + [i, i, i].join(',') + ')'; if (++i > 255) { clearInterval(timer); } }, 20); 
 #rect { height: 4em; } 
 <div id="rect"></div> 

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