HTML 5 Canvas Earth-Sun animation
Demonstrates simple animation using HTML 5 Canvas and JavaScript.
HTML
<!-- Business Web Technologies -->
<!-- School of Information Sytems -->
<!-- Curtni Univeristy -->
<canvas id="solarSystem" width="400" height="400"></canvas>
timeout (ms) <input id="timeout" type="text" value="60"/>
<button onclick="setDelay()">Set</button>
<!--Try entering different delays in miliseconds -->
<!-- 1000 miliseconds = 1 second -->
CSS
#solarSystem {
border: 1px solid black;
background: black;
}
body {
background: white;
}
JavaScript
// Preliminaries...
var solarSytem = document.getElementById("solarSystem");
var context = solarSystem.getContext('2d');
var timeout = 120; // Default timeout
var distance = 180; // distance of the earth from the sun in pixels
var angle = 0; // Degrees by which the earth is rotated about the sun
var earthSize = 10; // Size of the Earth in pixels
var sunSize = 30; // Size of the Sun in piexls
// JavaScript Object Notation defined here is used
// to store attributes of heavenly bodies
var sun = {x:200, y:200, radius: sunSize, color: "yellow"};
// Fancy mathematics to get the new position around a center point
function newPosition(center, distance, degrees, size, theColor) {
var radians = degrees * Math.PI / 180.0;
var xPosition = Math.cos(radians) * distance + center.x;
var yPosition = Math.sin(radians) * distance + center.y;
return {x: xPosition, y: yPosition, rad us: size, color: theColor};
}
// Draw a cirlce for a "heavenly body", which could be sun or earth
function drawHeavenlyBody(hb) {
context.beginPath();
context.arc(hb.x, hb.y, hb.radius, 0, 2.0*Math.PI, false);
context.fillStyle = hb.color;
context.fill();
context.closePath();
}
// Animate with a given timeoue
function animate () {
// Calcualgte the new position for earth given a new angel
var earth = newPosition(sun, distance, angle, earthSize, "blue");
// Clear the entire background to start the next frame
context.clearRect(0, 0, solarSystem.width, solarSystem.height);
// Draw the sun and the earth
drawHeavenlyBody(sun);
drawHeavenlyBody(earth);
// Calculate the new angle in incremeents of 10 degrees
angle += 1;
if (angle >= 360) {
angle = 0;
}
// Recursively call animate after the specified timeout
setTimeout(animate, timeout);
}
// Start animating!
animate();
function setDelay() {
timeout = document.getElementById("timeout").value;
}