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);
相關文章
相關標籤/搜索