canvas绘图工具加上JavaScript特效绘制出能动的太阳系

经过canvas绘图工具,绘制太阳系,用JavaScript函数让星球动起来,达到动画的效果。html

首先建立html并写出样式:canvas

<style>
    *{ padding:0px; margin:0px;}
    #canvas{ background:#000;}
</style>

<canvas id="canvas" width="900" height="900">
</canvas>

第一步调用函数绘制出轨道:
函数

var cxt = document.getElementById("canvas").getContext("2d");

function drawTrack(){
    for(var i=0;i<8;i++){
        cxt.beginPath();
        cxt.arc(450,450,(i+1)*45,0,360,false);
        cxt.closePath();
        cxt.strokeStyle = "#fff";
        cxt.stroke();
    }
}
drawTrack();

第二步建立绘制星球的函数:
工具

function Star(x,y,radius,cycle,sColor,eColor){
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.cycle = cycle;
    this.sColor = sColor;
    this.eColor = eColor;
    this.time = 0;
    this.color = null;
    this.draw = function(){
        cxt.save();                     
        cxt.translate(450,450);        
        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.sColor);
        this.color.addColorStop(1,this.eColor);
        cxt.fillStyle = this.color;
        cxt.fill();
        cxt.restore(); 
    }
}

第三部调用建立的函数绘制出星球:
动画

function Sun(){
    Star.call(this,0,0,30,0,"#f00","#f90");
}
function Mercurry(){
    Star.call(this,0,-45,6,87.7,"#a69697","#5c3e40");
}
function Venus(){
    Star.call(this,0,-90,14.23,224.7,"#c4bbac","#1f1315");
}
function Earth(){
    Star.call(this,0,-135,15,365.24,"#78b1e8","#050c12");
}
function Mars(){
    Star.call(this,0,-180,10,686.98,"#cec9b6","#76422d");
}
function Jupiter(){
    Star.call(this,0,-225,23,4332.589,"#a0a48e","#322222");
}
function Saturn(){
    Star.call(this,0,-270,21,10759.5,"#f7f9e3","#5c4533");
}
function Uranus(){
    Star.call(this,0,-315,8,30799.095,"#a7e1e5","#19243a");
}
function Neptune(){
    Star.call(this,0,-360,7,60152,"#0661b2","#1e3b37");
}
var sun = new Sun();
var mercurry = new Mercurry();
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();
sun.draw();
mercurry.draw();
venus.draw();
earth.draw();
mars.draw();
jupiter.draw();
saturn.draw();
uranus.draw();
neptune.draw();

到此,整个太阳系的轨道和全部星球都绘制出来了,剩下的就只有让这些星球按照各自的周期动起来this

第四补依然是调用函数rest

function move(){
    cxt.clearRect(0,0,1000,1000);
    drawTrack();
    sun.draw();
    mercurry.draw();
    venus.draw();
    earth.draw();
    mars.draw();
    jupiter.draw();
    saturn.draw();
    uranus.draw();
    neptune.draw();
}
setInterval(move,10);
相关文章
相关标签/搜索