又一波干货来了,如何使用canvas来画一个太阳系,我的天呢,太阳系都能画的出来,canvas真是太强了。有图有真相哦:
什么?说好的太阳系呢,老铁,怎么就看到一个行星?哈,是我偷了懒,我只画了个地球,其他的水星什么的不都是一样的道理吗,是不是?我都给你写出来了,你看着反而没有自己动手试验完善的激情了,是不是?我使用canvas只画了一个,剩下的几个行星你就画了吧,都是照着葫芦画瓢的事情,能画出来并理解了就是你掌握了。注意看代码里面的注释,这些虽然是我以前写的,不过我知道我习惯性的会把自己以前踩的坑都写到代码里面去,别把注释忽略了,指不定看到那句话你就豁然开朗,那岂不是我的荣幸?
太阳系html代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>使用canvas绘制太阳系</title> </head> <body> <section> <canvas id="sun" width="1000px" height="1000px"></canvas> </section> </body> </html>
canvas画太阳系javascript代码:
<script>
var num=0;
function sun(){
var canvas=document.getElementById("sun");
var cxt=canvas.getContext("2d");
cxt.clearRect(0,0,1000,1000);
//画太阳
cxt.beginPath();
cxt.arc(500,500,20,0,2*Math.PI,false);
//设置太阳的径向渐变色
//createRadialGradient(内圆x,内圆y,内圆半径,外圆x,外圆y,外圆半径);
//var sunColor=cxt.createRadialGradient(500,500,0,500,500,20);
var sunColor=cxt.createRadialGradient(490,510,0,500,500,20);// 立体感
//addColorStop(0-1,颜色):0-1之间的任意值,代表中间地带的百分比
sunColor.addColorStop(0,"#f00");
sunColor.addColorStop(1,"#f90");
cxt.fillStyle=sunColor;
cxt.fill();
cxt.closePath();
//画地球轨道
cxt.beginPath();
cxt.arc(500,500,100,0,2*Math.PI,false);
cxt.strokeStyle="white";
cxt.stroke();
cxt.closePath();
//画地球
cxt.save();
cxt.translate(500,500);
cxt.rotate((num%360)*Math.PI/180);
cxt.beginPath();
cxt.arc(0,-100,10,0,2*Math.PI,false);
//设置地球的径向渐变色
var earthColor=cxt.createRadialGradient(4,-105,0,0,-100,10);// 立体感
earthColor.addColorStop(0,"#78b1e8");
earthColor.addColorStop(1,"#050c12");
cxt.fillStyle=earthColor;
cxt.fill();
cxt.closePath();
cxt.restore();
num++;
if(num>=360){
num=0;
}
}
sun();
setInterval("sun()",100);
</script>
canvas绘制太阳系相关的css代码:
<style>
section{
border: 1px solid darkred;
width: 1000px;
height: 1000px;
background: black;
}
</style>