<!DOCTYPE html> <html> <head> <title>太阳系</title> </head> <body> <canvas id="canvas" width="1000" height="1000" style="background: #000">您的浏览器不支持</canvas> <script> var cxt = document.getElementById('canvas').getContext('2d');//设置2d环境 //轨道 function drawTrack() { for (var i = 0; i < 8; i++) { cxt.beginPath(); cxt.arc(500, 500, 50 * (i + 1), 0, 360, false); cxt.closePath(); cxt.strokeStyle = "#fff"; cxt.stroke(); } } //drawTrack(); //星球 function drawStar(x, y, radius, startColor, endColor, cycle) { //星球的坐标点、半径、颜色(开始、结束)、公转周期 this.x = x; this.y = y; this.radius = radius; this.startColor = startColor; this.endColor = endColor; this.cycle = cycle; //渐变颜色空对象 this.color = null; this.time = 0;//设置一个计时器 this.draw = function () { cxt.save(); cxt.translate(500, 500); cxt.rotate(this.time * (360 / this.cycle) * Math.PI / 180); cxt.beginPath(); cxt.arc(this.x, this.y, this.radius, 0, 360, false); cxt.closePath(); this.color = cxt.createRadialGradient(this.x, this.y, 0, this.x, this.y, this.radius);//径向渐变 this.color.addColorStop(0, this.startColor); this.color.addColorStop(1, this.endColor); cxt.fillStyle = this.color; cxt.fill(); cxt.restore(); this.time += 1; } } //创建一个太阳对象的构造函数 function Sun() { //第一个参数是this,从第二个参数开始才是drawStar方法的参数 drawStar.call(this, 0, 0, 20, "#f60", "#f90", 0); } //水星 function Mercury() { drawStar.call(this, 0, -50, 10, "#a69697", "#5c3e40", 87.7); } //金星 function Venus() { drawStar.call(this, 0, -100, 10, "#c4bbac", "#1f1315", 224.701); } //地球 function Earth() { drawStar.call(this, 0, -150, 10, "#78B1E8", "#050C12", 365.2422); } //火星 function Mars() { drawStar.call(this, 0, -200, 10, "#CEC9B6", "#76422D", 686.98); } //木星 function Jupiter() { drawStar.call(this, 0, -250, 10, "#C0A48E", "#322222", 4332.589); } //土星 function Saturn() { drawStar.call(this, 0, -300, 10, "#F7F9E3", "#5C4533", 10759.5); } //天王星 function Uranus() { drawStar.call(this, 0, -350, 10, "#A7E1E5", "#19243A", 30799.095); } //海王星 function Neptune() { drawStar.call(this, 0, -400, 10, "#0661B2", "#1E3B73", 164.8 * 365); } var sun = new Sun(); var mercury = new Mercury(); var venus = new Venus(); var earth = new Earth(); var mars = new Mars(); var jupiter = new Jupiter(); var saturn = new Saturn(); var uranus = new Uranus(); var neptune = new Neptune(); function drawAll() { cxt.clearRect(0, 0, 1000, 1000); //先画轨道 drawTrack(); //画行星 sun.draw(); mercury.draw(); venus.draw(); earth.draw(); mars.draw(); jupiter.draw(); saturn.draw(); uranus.draw(); neptune.draw(); } setInterval(drawAll, 10); </script> </body> </html>
时间: 2024-10-12 00:52:40