1. Registered User
Join Date
Oct 2012
Posts
16

## Color problem

Hi

I'm making a field of asteroids and try to change colors in two ways. Btw I'm a beginner with this.

First is to have all the androids colored randomly and second is two have them colored in lets say 3 different predefined colors.

Thanks guys...

Code:
```\$(document).ready(function() {
var canvas = \$("#myCanvas");
var context = canvas.get(0).getContext("2d");
var canvasWidth = canvas.width();
var canvasHeight = canvas.height();
\$(window).resize(resizeCanvas);

function resizeCanvas() {
canvas.attr("width", \$(window).get(0).innerWidth);
canvas.attr("height", \$(window).get(0).innerHeight);
canvasWidth = canvas.width();
canvasHeight = canvas.height();
};

resizeCanvas();

var playAnimation = true;
var startButton = \$("#startAnimation");
var stopButton = \$("#stopAnimation");
startButton.hide();
startButton.click(function() {
\$(this).hide();
stopButton.show();
playAnimation = true;
animate();
});

stopButton.click(function() {
\$(this).hide();
startButton.show();
playAnimation = false;
});

var Asteroid = function(x, y, radius, color) {
this.x = x;
this.y = y;
this.color = color;
this.vX = vX;
this.vY = vY;
};

var asteroids = new Array();
for (var i = 0; i < 1000; i++) {
var x = 20+(Math.random()*(canvasWidth-40));
var y = 20+(Math.random()*(canvasHeight-40));
var vX = Math.random()*4-2;
var vY = Math.random()*4-2;
var color = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
asteroids.push(new Asteroid(x, y, radius, vX, vY, color));
};

function animate() {
context.clearRect(0, 0, canvasWidth, canvasHeight);
//context.fillStyle = "rgb(255, 255, 255)";
var asteroidsLength = asteroids.length;
for (var i = 0; i < asteroidsLength; i++) {
var tmpAsteroid = asteroids[i];
tmpAsteroid.x += tmpAsteroid.vX;
tmpAsteroid.y += tmpAsteroid.vY;

tmpAsteroid.vX *= -1;
} else if (tmpAsteroid.x+tmpAsteroid.radius > canvasWidth) {
tmpAsteroid.vX *= -1;
};
tmpAsteroid.vY *= -1;
} else if (tmpAsteroid.y+tmpAsteroid.radius > canvasHeight) {
tmpAsteroid.vY *= -1;
};

context.beginPath();
context.arc(tmpAsteroid.x, tmpAsteroid.y, tmpAsteroid.radius, 0, Math.PI*2, false);
context.closePath();
context.fill();
};
if (playAnimation) {
setTimeout(animate, 33);
};
};

animate();
});```

2. Registered User
Join Date
Oct 2012
Location
Gujarat, India.
Posts
35
Well, try this.

3. Code:
```function oneOfManyColors(){
var colors=["#ff6622", "#00ff00", "#0088ff", "#ff0000", "#ff8800"]; //and so on
return colors[ Math.floor(colors.length * Math.random()) ];
}```