1. 程式人生 > >HTML5 + CSS3 實現地球繞太陽公轉

HTML5 + CSS3 實現地球繞太陽公轉

ans bubuko ram ini mage 實現 serve gif relative

使用的是正面視角,主要是用 HTML5 + CSS3 來實現,JS只是用來畫圖。

test.html:

<!DOCTYPE html> 
<html> 
<head>
    <meta charset="utf-8" />
    <title>地球-太陽自轉與公轉</title> 
    <link type="text/css" rel=‘stylesheet‘ href="test.css"></link> 
</head> 
<body> 
    <div class
="box"> <canvas id="sun" width="150px" height="150px"></canvas> <canvas id="earth" width="50px" height="50px"></canvas> </div> <script src="test.js"></script> </body> </html>

註意<canvas>是行內置換元素,可以設置寬高和內外邊距。

test.css:

*{
    margin
: 0; padding: 0; } .box{ width: 150px; height: 150px; margin: 100px auto; position: relative; transform-style: preserve-3d; /*perspective: 10000px;*/ animation: sun linear 365s infinite; /*地球公轉*/ } #sun{ position: absolute; animation: sun linear 26.7s infinite; /*太陽自轉+誤差
*/ } #earth{ margin: 50px; position: absolute; transform: translateZ(600px); animation: earth linear 1s infinite; /*地球自轉*/ } @keyframes sun{ from{transform: rotateY(0deg);} to{transform: rotateY(360deg);} } @keyframes earth{ from{transform: translateZ(600px) rotateY(0deg);} to{transform: translateZ(600px) rotateY(360deg);} }

其中1 s = 1 天。

.box加上一個較大的 perspective 屬性,想象自己漂在太空中較遠處某個點觀察地球和太陽;不加 perspective 屬性相當於站在無窮遠處觀察。

test.js:

var sun = document.getElementById("sun").getContext(‘2d‘),
    earth = document.getElementById(‘earth‘).getContext(‘2d‘),
    gra1 = sun.createRadialGradient(75,75,0,75,75,75),
    gra2 = earth.createRadialGradient(25,25,0,25,25,25);
gra1.addColorStop(0,‘#ffff00‘);
gra1.addColorStop(1,‘#ff9900‘);
sun.arc(75,75,75,0,2 * Math.PI);
sun.fillStyle = gra1;
sun.fill();
gra2.addColorStop(0,‘#78b1e8‘);
gra2.addColorStop(1,‘#1c4364‘);
earth.arc(25,25,25,0,2 * Math.PI);
earth.fillStyle = gra2;
earth.fill();

效果圖:

技術分享圖片

HTML5 + CSS3 實現地球繞太陽公轉