1. 程式人生 > >canvas基礎學習(二)-線條的屬性與星空和圖形變換

canvas基礎學習(二)-線條的屬性與星空和圖形變換


以下是星空程式碼實現:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<canvas id="canvas" style="border: 1px solid #aaa;display: block;margin: 50px auto;">
			你當前的瀏覽器不支援canvas,請更換瀏覽器再試。
		</canvas>
		
		<script>
			window.onload = function(){
				var canvas = document.getElementById("canvas");
				
				canvas.width = 800;
				canvas.height = 500;
				
				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;
					var dis = Math.min(x,canvas.width-x,y,canvas.height-y);
					if(dis >= r){
						drawStar(context, r, x, y, a);
					}
					
				}
				
				
			}
			function drawStar(cxt, R, x, y, rot){
				
				cxt.save();
				
				cxt.translate(x,y);
				cxt.rotate(rot/180*Math.PI);
				cxt.scale(R,R);
				
				starPath(cxt);
				
				cxt.fillStyle = "#f3b";
//				cxt.strokeStyle = "#fd5";
//				cxt.lineWidth = 3;
//				cxt.lineJoin = "round";
				
				cxt.fill();
				//cxt.stroke();
				
				cxt.restore();
				
				}
			function starPath(cxt){
				cxt.beginPath();
				for(var i = 0; i < 5; i ++){
					cxt.lineTo(Math.cos((18+i*72)/180*Math.PI),
						   		-Math.sin((18+i*72)/180*Math.PI));
					cxt.lineTo(Math.cos((54+i*72)/180*Math.PI)*0.5,
						   		-Math.sin((54+i*72)/180*Math.PI)*0.5)
				}
				cxt.closePath();
			}
				
		</script>
		
	</body>
</html>