Along the way you'll also learn a thing or two about Celestial Mechanics.
I've deliberately broken up this tutorial to keep things as understandable as possible. Each part contains workable code you can run locally on your machine.
Each code example is a pre-requisite for the next one, so I don't recommend skipping ahead. For example, in order to calculate planetary positions, you will first need to convert the commonly known Gregorian date into a Julian date.
I hope this tutorial helps you to create your own JS Solar System simulator. Have fun!
I. CREATE LAYERED HTML CANVAS
We start off by creating our foundation using an HTML canvas.
This is our starting point upon which we keep building additional functionality in the subsequent sections.
BACKGROUND LAYER CANVAS
Used for static graphical elements (e.g. rendering Sun at center of canvas)
FOREGROUND LAYER CANVAS
Used for moving graphical elements (e.g. dynamic text elements)
On the right you see the layered HTML canvas trying to run at 20FPS. The sun is rendered on the background canvas as it doesn't move. The text is rendered on the foreground canvas as values need to be
In order to start using the Keplerian elements and calculate the position of the planets, we need to use the Julian calendar. Since we currently use the Gregorian calendar,
GREGORIAN DATE = JAN 1, 2150
The Gregorian Calendar is the most widely used calendar today.
JULIAN DAY = 2506332
Julian Calendar expressed in Julian Day Number (Day 0 = JAN 1, 4713BC)
JULIAN CENTURIES SINCE J2000 = 1.5
Julian Centuries since the reference date or Epoch (JAN 1, 2000AD)
Gregorian date to Julian Centuries since J2000
III. CALCULATE ELEMENTS USING JULIAN DATE
Now that we have the Julian date and how many centuries after J2000 this is, we can apply that to calculate planet positions using JPL's
Keplerian elements for Approximate Positions of the Major Planets.
In the example on the right we are calculating the Keplerian elements for Mars based on the Gregorian input date.
For a refresher on the Keplerian elements go HERE.
As you can see, the orbit SIZE, orbit SHAPE and orbit ORIENTATION, captured in the first five Keplerian elements, don't change much.
Its only the orbit POSITION "L" that changes as time passes by.
Now that we can calculate the Keplerian elements for any date, the last step is to determine the Heliocentric Ecliptic Coordinates of the planet.
In order to do this we will need two things:
The view of Mars itself (the red dot) is a top-down representation and therefore the Z coordinate is not being used.