Wasteland
Wasteland

Reputation: 5399

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);

Upvotes: 0

Views: 44

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075427

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>

Upvotes: 1

Related Questions