练习canvas,跟着教材做一个绘制五角星的特效,大家可以复制代码在本地查看效果。
分析:五角星有十个定点,五个外顶点,五个内顶点,可以看成顶点分别在两个圆上,其中假设外顶点所在圆的半径为R,内顶点所在圆的半径为r,画图分析可以知道每个顶点在坐标中的位置,其中方法drawStar(cxt,r,R,x,y)五个参数分别表示画布、小圆半径、大圆半径、五角星x轴偏移量、y轴偏移量。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绘制五角星</title>
</head>
<body>
<canvas id="myConvas"></canvas>
<script type="text/javascript">
window.οnlοad=function(){
var canvas=document.getElementById("myConvas");
canvas.width=800;//设置画布的宽度
canvas.height=800;//设置画布的高度
var context=canvas.getContext("2d");
context.lineWidth=10;
drawStar(context,100,200,400,400);
}
function drawStar(cxt,r,R,x,y){
cxt.beginPath();
for(var i=0;i<5;i++){
cxt.lineTo(Math.cos((18+i*72)/180*Math.PI)*R+x,-Math.sin((18+i*72)/180*Math.PI)*R+y);
cxt.lineTo(Math.cos((54+i*72)/180*Math.PI)*r+x,-Math.sin((54+i*72)/180*Math.PI)*r+y);
}
cxt.closePath();
cxt.stroke();
}
</script>
</body>
</html>
绘制一片星空:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>一片星空</title>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script type="text/javascript">
window.οnlοad=function(){
var canvas=document.getElementById("myCanvas");
canvas.width=800;
canvas.height=800;
var context=canvas.getContext("2d");
context.fillStyle="black";
context.fillRect(0,0,canvas.width,canvas.height);
for(var i=0;i<200;i++){
var r=Math.random()*10+10;
var x=Math.random()*canvas.width;
var y=Math.random()*canvas.height;
var a=Math.random()*360;
drawStar(context,x,y,r,r/2.0,a);
}
}
function drawStar(cxt,x,y,outerR,innerR,rot){
cxt.beginPath();
for(var i=0;i<5;i++){
cxt.lineTo(Math.cos((18+i*72-rot)/180*Math.PI)*outerR+x,
-Math.sin((18+i*72-rot)/180*Math.PI)*outerR+y);
cxt.lineTo(Math.cos((54+i*72-rot)/180*Math.PI)*innerR+x,
-Math.sin((54*i*72-rot)/180*Math.PI)*innerR+y);
}
cxt.closePath();
cxt.fillStyle="#fb3";
cxt.strokeStyle="#fd5";
cxt.lineWidth=2;
cxt.lineJoin="round";
cxt.fill();
cxt.stroke();
}
</script>
</body>
</html>