为什么星星固定在左上角了?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>星空</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
body{
text-align: center;
}
</style>
</head>
<body>
<canvas id="canvas" >浏览器不支持的时候显示</canvas>
<script type="text/javascript">
window.onload = function() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 800;
context.fillStyle = '#000';
context.fillRect(0,0,canvas.width,canvas.height);
for(var i=0;i<200;i++) {
var r = Math.random()*10+10; // 10~20
var x = Math.random()*canvas.width;
var y = Math.random()*canvas.height;
var a = Math.random()*360;
drawStart(context,r/2.0,r,x,y,a);
}
}
function drawStart(cxt,x,y,R,rot) {
// 绘制出在(x,y),大小为R,旋转角度为rot的五角星
// 位移 translate(x, y)
// 旋转 rotate(deg);
// 缩放 scale(sx,sy)
cxt.save();
cxt.translate(x, y);
cxt.rotate(rot/180*Math.PI);
startPath(cxt);
cxt.fillStyle = '#fb3';
cxt.strokeStyle = '#fd5';
cxt.lineWidth = 3;
cxt.lineJoin = 'round';
cxt.fill();
cxt.stroke();
cxt.restore();
}
// 标准五角星的路径
function startPath(cxt) {
cxt.beginPath();
for(var i=0;i<5;i++) {
cxt.lineTo(Math.cos((18+i*72)/180*Math.PI)*20,
-Math.sin((18+i*72)/180*Math.PI)*20);
cxt.lineTo(Math.cos((54+i*72)/180*Math.PI)*0.5*20,
-Math.sin((54+i*72)/180*Math.PI)*0.5*20);
}
cxt.closePath();
}
</script>
</body>
</html>