Last Good Quote: Son's are the seasoning on our lives. - Someone on Facebook

Saturday, March 22

JS Starfield

The following will create a flowing field of stars on a black background. Used the HTML5 Canvas element to create this effect:

<script>

var canvas = "";
var context = "";
var stars = new Array();



function loadStarfield()
{
canvas = document.getElementById("canvas_starfield");
context = canvas.getContext("2d");

addNewStars(100);

//stars[stars.length-1].starSize = 50;
//stars[stars.length-1].drawColor = "#333";
//stars[stars.length-1].position.x = -10;
//stars[stars.length-1].position.y = 150;
//stars[stars.length-1].velocity.x = 1;


starfieldLoop();

}


function starfieldLoop()
{
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);

for(var i=0;i<stars.length;i++)
{
drawStar(stars[i]);
stars[i].animate();
}

window.requestAnimationFrame(starfieldLoop);

}

function drawStar(star)
{
  var position = star.position;
  context.fillStyle = star.drawColor;
  context.beginPath();
  context.arc(position.x, position.y, star.starSize, 0, Math.PI * 2);
  context.closePath();
  context.fill();
}




function addNewStars(numStars)
{
for (var i = 0; i < numStars; i++)
{
stars.push(new Star());
}
}

function Star() {
  this.position = new Vector(randBetween(0,canvas.width),randBetween(0,canvas.height)); // Vector
  this.velocity = new Vector(randBetween(1,5),0);
  var c = randBetween(0,9);
  this.drawColor = "#FFF"; //"#" + c + "" + c + "" + c; // So we can tell them apart from Fields later
  this.starSize = randBetween(1,1);
}

Star.prototype.animate = function()
{
this.position.add(this.velocity);

if(this.position.x > canvas.width)
{
this.position.x = 0;
}
}



//////////////////////////////////////////////////////////////////////////////////////////////
//
// Utils
//
//////////////////////////////////////////////////////////////////////////////////////////////
function randBetween(min, max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}

function Vector(x, y) {
  this.x = x || 0;
  this.y = y || 0;
}

// Add a vector to another
Vector.prototype.add = function(vector) {
  this.x += vector.x;
  this.y += vector.y;
}

// Gets the length of the vector
Vector.prototype.getMagnitude = function () {
  return Math.sqrt(this.x * this.x + this.y * this.y);
};

// Gets the angle accounting for the quadrant we're in
Vector.prototype.getAngle = function () {
  return Math.atan2(this.y,this.x);
};

// Allows us to get a new vector from angle and magnitude
Vector.fromAngle = function (angle, magnitude) {
  return new Vector(magnitude * Math.cos(angle), magnitude * Math.sin(angle));
};

</script>

<canvas id="canvas_starfield" width="600" height="300"
style="
border:5px solid black;">
</canvas>
<script>
loadStarfield();
</script>



0 comments:

Post a Comment

Followers