let r0 = [3, 8, 10, 5]//行星半径
let r = [70, 100, 150, 200]//行星轨道半径
let timer = [12, 30, 60, 120]//公转周期
canvas的translate方法是将坐标原点移动至目标位置
rotate方法是旋转坐标原点一定角度。
save保存当前状态
restore恢复保存的状态
<!DOCTYPE html>
<html>
<head>
<title>space</title>
</head>
<body>
<canvas id='canvas' width="500" height="500"></canvas>
<script>
var canvas = document.getElementById('canvas')
canvas.style.backgroundColor = "#ddd"
var cc = canvas.getContext("2d")
var gradient = cc.createRadialGradient(250, 250, 0, 250, 250, 60)
gradient.addColorStop(0, 'red')
gradient.addColorStop(1, 'white')
var sun = {
x: 250, y: 250, r: 30
}
let r0 = [3, 8, 10, 5]
let r = [70, 100, 150, 200]
let timer = [12, 30, 60, 120]
init()
function init() {
cc.clearRect(0, 0, 1080, 1080)
//绘制恒星
planet(sun.x, sun.y, sun.r, gradient)
cc.save()
//绘制行星轨道1
for (let i = 0; i < 4; i++) road(sun.x, sun.y, r[i])
cc.translate(sun.x, sun.y);// 将中心坐标移至太阳中心
let time = new Date();
for (let i = 0; i < 4; i++) {
cc.save()
//旋转
cc.rotate(2 * Math.PI * (1 / timer[i] * 60 * time.getMinutes() + 1 / timer[i] * time.getSeconds() + 1 / timer[i] / 1000 * time.getMilliseconds()))
//绘制行星
planet(0, r[i], r0[i])
if (i == 2) {
cc.translate(0, r[i])// 将中心坐标移至行星中心
road(0, 0, 30)
cc.rotate(-2 * Math.PI / 3 * time.getSeconds() - 2 * Math.PI / 3000 * time.getMilliseconds());
planet(0, 30, 2)
}
cc.restore()
}
cc.restore()
requestAnimationFrame(init)
}
//绘制轨道
function road(x, y, r, style = 'black') {
cc.beginPath()
cc.strokeStyle = style
cc.arc(x, x, r, 0, Math.PI * 2)
cc.stroke()
}
//绘制行星
function planet(x, y, r, style = 'black') {
cc.beginPath()
cc.fillStyle = style
cc.arc(x, y, r, 0, Math.PI * 2)
cc.fill()
}
</script>
</body>
</html>