Skip to content

Instantly share code, notes, and snippets.

@mdkq
Created June 30, 2017 00:36
Show Gist options
  • Save mdkq/b123d35713d121d8bcbd710c02ecdbb7 to your computer and use it in GitHub Desktop.
Save mdkq/b123d35713d121d8bcbd710c02ecdbb7 to your computer and use it in GitHub Desktop.
Rotating parallax star galaxy (svg). Tips to clean up code appreciated
window.onload = function() {
var svgNS = "http://www.w3.org/2000/svg"
var svgGroup = document.getElementById("stars");
var galaxy = document.getElementById("galaxy").getBoundingClientRect();
var center = { x: galaxy.width / 2, y: galaxy.height / 2 };
var stars = []
window.onresize = function() {
galaxy = document.getElementById("galaxy").getBoundingClientRect();
center = { x: galaxy.width / 2, y: galaxy.height / 2 };
};
// OPTIONS ///////////////////////////////////////////////////////////////////
var maxRad = Math.sqrt(Math.pow(center.x, 2) + Math.pow(center.y, 2));
var starCount = 200;
var speed = 0.1;
var innerRadius = 200;
var minSize = 0.5;
var maxSize = 2;
//////////////////////////////////////////////////////////////////////////////
for(var i = 0; i < starCount; ++i) {
// add new star
var star = document.createElementNS(svgNS, "circle");
// set basic tag attributes
star.setAttribute("class", "star");
star.setAttribute("fill", "white");
star.setAttribute("stroke", "none");
star.setAttribute("cx", center.x);
star.setAttribute("cy", center.y);
star.setAttribute("r", Math.random() * (maxSize - minSize) + minSize);
// set custom attributes for calculations
star.speed = parseFloat(star.getAttribute("r")) * speed;
star.angle = Math.random() * 360;
star.radius = Math.random() * (maxRad - innerRadius) + innerRadius;
// add to internal array and svg group
stars.push(star);
svgGroup.appendChild(star);
}
function rotate() {
stars.forEach(function(star) {
// increase the angle of rotation
star.angle += star.speed * Math.PI / 180;
// calculate the new star coords
star.setAttribute("cx", center.x + star.radius * Math.cos(star.angle));
star.setAttribute("cy", center.y + star.radius * Math.sin(star.angle));
});
requestAnimationFrame(rotate);
}
rotate();
};
<!doctype html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<svg id="galaxy">
<g id="stars"></g>
</svg>
<script src="js/galaxy.js"></script>
</body>
</html>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
body {
background-color: #222;
}
#galaxy {
width: 100%;
height: 100%;
}
#stars {
width: 100%;
height: 100%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment