I have created an array of color values which represents a smooth transition of colors from red to blue.
Now I want this array to take you from red to blue and back again. The obvious solution is to append the reverse of the array to the array.
I have written code to do it, but it isn't working as I understand it should. Instead, it's creating the reversed array, repeated. Instead of "Red to Blue, Blue to Red", it's going "Blue to Red, Blue To Red".
Clearly, there's some behavior of arrays in javascript that I haven't grasped yet.
What should I be doing?
My first attempt is this:
colors = colors.concat(colors.reverse());
Based on the first stackoverflow answer, I tried this:
var arrayCopy = colors;
arrayCopy.reverse();
colors = colors.concat(arrayCopy);
But this produces identical results!
For context, here's the surrounding code:
///////////////////////////////////////////////////////////
// Creating the array which takes you from Red to Blue
//
var colorSteps = 400;
var startColor = [255, 0, 0];
var endColor = [0, 127, 255];
var steps = new Array();
var j = 0;
for (j = 0; j < 3; ++j) {
steps[j] = (endColor[j] - startColor[j]) / colorSteps;
}
var colors = Array();
for (j = 0; j < colorSteps; ++j) {
colors[j] = [
Math.floor(startColor[0] + steps[0] * j),
Math.floor(startColor[1] + steps[1] * j),
Math.floor(startColor[2] + steps[2] * j)
];
}
////////////////////////////////////////////////////////
// Here's the bit where I'm trying to make it a mirror
// of itself!
//
// It ain't working
//
colors = colors.concat(colors.reverse());
///////////////////////////////////////////////////////
// Demonstrating what the colors are
//
j = 0;
var changeColorFunction = function () {
if (++j >= colors.length) {
j = 0;
}
var colorName = "rgb(" + colors[j][0] + ", " + colors[j][1] + ", " + colors[j][2] + ")";
debugText.style.background = colorName;
debugText.innerHTML = j;
}
setInterval(changeColorFunction, 10);
The problem with:
colors = colors.concat(colors.reverse());
... is that colors.reverse()
mutates the colors
array itself, meaning that you're appending a reversed array to an already-reversed array. Try this instead:
colors = colors.concat(colors.slice().reverse());
Copy your colors
array to somewhere first. reverse
changes the array itself, not merely returns a reverted one.
UPDATE
Code sample:
colors.concat(colors.slice(0).reverse());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With