在MDN官网学习了canvas便做了个小练习来加强对canvas的了解,巩固学到的新知识。
下面放图:
<html>
<head>
<title>canvas</title>
</head>
<body>
<!--新建一个canvas元素-->
<canvas id="mycanvas" width="600" height="600" style="border:1px solid #aaaaaa;" >your brower not support canvas!</canvas>
</body>
<script type="text/javascript">
draw();
function draw(){
//获取canvas元素
var canvas = document.getElementById('mycanvas');
//渲染上下文
var ctx = canvas.getContext('2d');
ctx.fillRect(0,0,600,600);//将整个canvas上一层黑色
//在画布中间绘制太阳
var gradient = ctx.createRadialGradient(300,300,10,300,300,15);//设置渐变颜色
gradient.addColorStop(0,'#ffff00');//添加起始颜色
gradient.addColorStop(1,'rgba(250,250,0,0)');//添加
ctx.fillStyle = gradient;
ctx.arc(300,300,15,0,2*Math.PI);
ctx.fill();
var a = 0;
var b = 0;
draw_star(ctx,a,b,150,300,300,0.5,'#ad0087')
draw_star(ctx,a,b,150,300,300,0.5,'#ad0087')
draw_star(ctx,a,false,180,300,300,0.2,'#28ff28')
draw_star(ctx,Math.PI/3,false,220,300,300,0.13,'#f9f900')
draw_star(ctx,-Math.PI/3,b,240,300,300,0.063,'#00ff99')
}
var is_up = true;//判断运动方向
/**
* @param ctx ctx对象
* @param a 行星起始位置,以π为单位
* @param b 卫星起始位置,以π为单位
* @param r 半径,也就是行星与太阳的距离
* @param sun_x 太阳的X坐标
* @param sun_y 太阳的Y坐标
* @param speed 运行速度
* @param color 颜色
*/
function draw_star(ctx,a,b,r,sun_x,sun_y,speed,color){
is_up = a>=Math.PI?false:true;//判断行星所在位置的角度,如果大于180°则修改运动方向
a = a>=Math.PI*2?0:a;//判断行星所在位置角度是否大于360°,如果大于360°则重置角度为0°
if(b!==false){
b>Math.PI*2?b=0:b=b;//判断卫星所在位置角度是否大于360°,如果大于360°则重置角度为0°
b+=Math.PI/80*speed;//设置b的变化速率,即行星运行的角度
}
var x = sun_x-(r*Math.cos(a));//利用三角函数计算行星所在的X坐标
var y = Math.sqrt(Math.pow(r,2)-Math.pow((x-sun_x),2))+sun_y;//利用圆的方程式计算行星所在的Y坐标
y = is_up?y:Math.abs(y-(2*sun_y));//判断行星的方向
ctx.beginPath();//新建一条路径,用来覆盖上一次绘制的行星,可以把这段删注释掉,看看效果
ctx.fillStyle = "#000";//因为背景是黑色的所以把样式设为黑色
ctx.arc(x,y,10,0,2*Math.PI);//绘制背景
ctx.fill();//填充
a+=Math.PI/1800*speed;//设置a的变化速率,即行星运行的速度
y = Math.sqrt(Math.pow(r,2)-Math.pow((x-sun_x),2))+sun_y;//利用圆的方程式计算行星所在的Y坐标
is_up?y=y:y=Math.abs(y-(2*sun_y));//判断行星的方向
var gradient_eath = ctx.createRadialGradient(x,y,5,x,y,10);//添加渐变
gradient_eath.addColorStop(0,color);//设置中心颜色
gradient_eath.addColorStop(1,'rgba(0,0,0,0)');//设置边缘颜色
ctx.beginPath();//新建一条路径
ctx.fillStyle = gradient_eath;//设置填充样式为渐变
ctx.arc(x,y,10,0,2*Math.PI);//绘制行星
ctx.fill();//填充
b?draw_mouth(ctx,x,y,a,is_up,b,speed):b=b;//判断是否存在b如果存在则绘制当前行星的卫星
setTimeout(function(){draw_star(ctx,a,b,r,sun_x,sun_y,speed,color)},0.1);//进行循环
}
//绘制卫星方法。基本与绘制行星差不多,就不详细作解了
function draw_mouth(ctx,x,y,a,is_up,b,speed){
b>Math.PI?is_up = false:is_up=true;
x2 = x-(20*Math.cos(b-(Math.PI/80*speed)));
y2 = Math.sqrt(400-Math.pow((x2-x),2))+y;
is_up?y2=y2:y2=y-Math.abs(y-y2);
ctx.beginPath();
ctx.fillStyle = '#000';
ctx.arc(x2,y2,6,0,2*Math.PI);
ctx.fill();
x1 = x-(20*Math.cos(b));
y1 = Math.sqrt(400-Math.pow((x1-x),2))+y;
is_up?y1=y1:y1=y-Math.abs(y-y1);
ctx.beginPath();
ctx.fillStyle = 'red';
ctx.arc(x1,y1,5,0,Math.PI*2);
ctx.fill();
}
</script>
</html>