HTML5 + CSS3 实现地球绕太阳公转
时间: 2023-08-14 11:06:39 浏览: 72
要实现地球绕太阳公转,可以使用HTML5的canvas标签和CSS3的animation属性。
首先,在HTML中创建一个canvas标签,并设置其宽度和高度:
```html
<canvas id="canvas" width="600" height="600"></canvas>
```
然后,使用JavaScript获取canvas元素并获取其上下文:
```javascript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
```
接下来,我们需要绘制太阳和地球。可以使用canvas的arc方法绘制圆形:
```javascript
// 绘制太阳
ctx.fillStyle = "yellow";
ctx.beginPath();
ctx.arc(300, 300, 50, 0, Math.PI * 2);
ctx.fill();
// 绘制地球
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(150, 300, 20, 0, Math.PI * 2);
ctx.fill();
```
现在,我们需要使用CSS3的animation属性来实现地球绕太阳公转。我们可以使用以下样式:
```css
#canvas {
animation: rotation 10s linear infinite;
}
@keyframes rotation {
from {
transform: rotate(0);
}
to {
transform: rotate(360deg);
}
}
```
这将使canvas元素在10秒钟内旋转360度,并且动画将无限循环。
完整的HTML和CSS代码如下所示:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>地球绕太阳公转</title>
<style>
#canvas {
animation: rotation 10s linear infinite;
}
@keyframes rotation {
from {
transform: rotate(0);
}
to {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="600"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// 绘制太阳
ctx.fillStyle = "yellow";
ctx.beginPath();
ctx.arc(300, 300, 50, 0, Math.PI * 2);
ctx.fill();
// 绘制地球
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(150, 300, 20, 0, Math.PI * 2);
ctx.fill();
</script>
</body>
</html>
```
希望能对你有所帮助!