利用html5画出五角星画出星空

利用html5画出五角星

(在慕课网学习<canvas>标签后代码总结)

五角星的格定点坐标该如何定位?原理图如下:




源代码:
<!DOCTYPE HTML>
<html>
<body>

<canvas id="canvas" width="600" height="600" style="border:1px solid #c3c3c3;">
</canvas>

<script type="text/javascript">

window.onload = function(){
	var canvas = document.getElementById("canvas");
	var context=canvas.getContext("2d"); 

	//绘制和画布一样大小的黑色矩形
	context.fillStyle = "black";
	context.fillRect(0,0,canvas.width,canvas.height);
	
	
	//调用构造五角星函数,并随机产生多个五角星
	for(var i = 0;i < 130;i++){
		//随机大圆半径
		var r = Math.random() * 10 + 10;    
		var x =Math.random() * canvas.width;
		var y =Math.random() * canvas.height;
		//随机旋转角0-360
		var a =Math.random() * 360;
		drawstar(context,x,y,r,r/2.0,a);

	}

}	

//定义五角星函数,注意在javascript中三角函数要求角度转换为弧度,x,y为五角星的偏移量,rot为图形旋转角度
	function drawstar(cxt,x,y,outerR,innnerR,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)*innnerR + x,-Math.sin((54 + i * 72 - rot)/180*Math.PI)*innnerR + y);
		}
	
		cxt.closePath();
		
		//状态
		cxt.fillStyle = "#fd5";
		cxt.strokeStyle = "#fb5";
		cxt.lineWidth = 3;
		cxt.lineJoin = "round";
		
		//执行
		cxt.fill();
		cxt.stroke();
	}

</script>

</body>
</html>

星空效果图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值