[codepen_embed height=”412″ theme_id=”dark” slug_hash=”JwBEjw” default_tab=”result” user=”briancribb”]See the Pen <a href=’https://codepen.io/briancribb/pen/JwBEjw/’>Canvas Solar System</a> by Brian Cribb (<a href=’https://codepen.io/briancribb’>@briancribb</a>) on <a href=’https://codepen.io’>CodePen</a>.[/codepen_embed]
Here’s a swanky little bit of animation from the HTML5 Canvas. If you don’t see it, then your browser doesn’t support canvas, which means that you’re using an old version of Internet Explorer. (You should stop doing that.) The goal was to see what I could draw programmatically with the canvas API.
It started with just the sun, but then I wanted some planets, then a moon, and finally I added a starfield. The neat thing is the complete lack of canvas rotation. Instead of using the rotation method of the canvas, the sun is being drawn a little differently upon each interval.
Another neat thing is the use of classes. Well, object prototypes, really. But they’re similar. Kind of. Anyway, there are two different prototypes for this animation. There’s a Sun and a Planet. (That little moon is just a planet which is targeted on another planet instead of the sun.) They have their own methods and properties, so a simple loop can tell them all to adjust their positions before the next redraw. Run that every few milliseconds, and you have a smooth animation.
Another cool bit is the way I change up for mobile devices. The starfield tends to be a bit much for my iPhone, so I check the size of the browser window before the application starts. If you’re on a desktop, it runs normally at any size. If you start with a smaller window (like a mobile device) then an image-based starfield is loaded instead. You can try it from a desktop if you shrink the window first and then refresh. Not bad.