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.radius = radius; 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 radius = 2+Math.random()*30; 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; if (tmpAsteroid.x-tmpAsteroid.radius < 0) { tmpAsteroid.x = tmpAsteroid.radius; tmpAsteroid.vX *= -1; } else if (tmpAsteroid.x+tmpAsteroid.radius > canvasWidth) { tmpAsteroid.x = canvasWidth-tmpAsteroid.radius; tmpAsteroid.vX *= -1; }; if (tmpAsteroid.y-tmpAsteroid.radius < 0) { tmpAsteroid.y = tmpAsteroid.radius; tmpAsteroid.vY *= -1; } else if (tmpAsteroid.y+tmpAsteroid.radius > canvasHeight) { tmpAsteroid.y = canvasHeight-tmpAsteroid.radius; 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(); });



Reply With Quote
Bookmarks