Created
March 29, 2014 09:54
-
-
Save baniol/9851680 to your computer and use it in GitHub Desktop.
basic canvas animation, javascript, requestAnimationFrame, solar system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<style type="text/css"> | |
/*canvas{ width: 300px; height: 300px;}*/ | |
</style> | |
</head> | |
<body> | |
<canvas id="canvas" width="300" height="300"></canvas> | |
<script type ="application/javascript" language="javascript"> | |
window.requestAnimFrame = (function() { | |
return window.requestAnimationFrame || | |
window.webkitRequestAnimationFrame || | |
window.mozRequestAnimationFrame || | |
window.oRequestAnimationFrame || | |
window.msRequestAnimationFrame || | |
function( /* function */ callback, /* DOMElement */ element) { | |
window.setTimeout(callback, 1000 / 60); | |
}; | |
})(); | |
var sun = new Image(); | |
var moon = new Image(); | |
var earth = new Image(); | |
init(); | |
animate(); | |
function init() { | |
sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png'; | |
moon.src = 'https://mdn.mozillademos.org/files/1443/Canvas_moon.png'; | |
earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png'; | |
// setInterval(draw, 100); | |
} | |
function animate() { | |
requestAnimFrame(animate); | |
draw(); | |
} | |
function draw() { | |
var ctx = document.getElementById('canvas').getContext('2d'); | |
ctx.globalCompositeOperation = 'destination-over'; | |
ctx.clearRect(0, 0, 300, 300); // clear canvas | |
ctx.fillStyle = 'rgba(0,0,0,0.4)'; | |
ctx.strokeStyle = 'rgba(0,153,255,0.4)'; | |
ctx.save(); | |
ctx.translate(150, 150); | |
// Earth | |
var time = new Date(); | |
ctx.rotate(((2 * Math.PI) / 60) * time.getSeconds() + ((2 * Math.PI) / 60000) * time.getMilliseconds()); | |
ctx.translate(105, 0); | |
ctx.fillRect(0, -12, 50, 24); // Shadow | |
ctx.drawImage(earth, -12, -12); | |
// Moon | |
ctx.save(); | |
ctx.rotate(((2 * Math.PI) / 6) * time.getSeconds() + ((2 * Math.PI) / 6000) * time.getMilliseconds()); | |
ctx.translate(0, 28.5); | |
ctx.drawImage(moon, -3.5, -3.5); | |
ctx.restore(); | |
ctx.restore(); | |
ctx.beginPath(); | |
ctx.arc(150, 150, 105, 0, Math.PI * 2, false); // Earth orbit | |
ctx.stroke(); | |
ctx.drawImage(sun, 0, 0, 300, 300); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello
Thanks for the code but it seemes that the images png are missing then it doesn't work