JS Starfield

August 30, 2022

The following will create aflowing field of stars on a black background. Used the HTML5 Canvas element tocreate 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(vari=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 (vari = 0; i < numStars; i++)
{
 stars.push(newStar());
}
}

function Star() {
  this.position = newVector(randBetween(0,canvas.width),randBetween(0,canvas.height)); // Vector
  this.velocity = newVector(randBetween(1,5),0);
  var c = randBetween(0,9);
  this.drawColor = "#FFF";//"#" + c + "" + c + "" + c; // So we can tellthem 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)
{
returnMath.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 quadrantwe're in
Vector.prototype.getAngle = function () {
  return Math.atan2(this.y,this.x);
};

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

</script>

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

 

Grow your business.
I am focused on helping start-ups in stabilizing and growing through strategy and analysis. Reach out to me today to start growing your business.
Start Now